如何将char数组转换回字符串?

How to convert a char array back to a string?(如何将char数组转换回字符串?)
本文介绍了如何将char数组转换回字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个字符数组:

char[] a = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};

我目前的解决方案是做

String b = new String(a);

但肯定有更好的方法吗?

But surely there is a better way of doing this?

推荐答案

不,这个解决方案是绝对正确的,而且非常少.

No, that solution is absolutely correct and very minimal.

但是请注意,这是一种非常不寻常的情况:因为 String 在 Java 中是专门处理的,所以即使 "foo" 实际上也是一个 String.因此,在普通代码中不需要将字符串拆分为单独的 char 并将它们重新连接起来.

Note however, that this is a very unusual situation: Because String is handled specially in Java, even "foo" is actually a String. So the need for splitting a String into individual chars and join them back is not required in normal code.

将此与 C/C++ 进行比较,其中 "foo" 您有一束 char 以一侧的零字节和 string 另一方面,它们之间的许多转换都使用旧方法.

Compare this to C/C++ where "foo" you have a bundle of chars terminated by a zero byte on one side and string on the other side and many conversions between them due do legacy methods.

这篇关于如何将char数组转换回字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

quot;Char cannot be dereferencedquot; error(“Char 不能被取消引用错误)
Java Switch Statement - Is quot;orquot;/quot;andquot; possible?(Java Switch 语句 - 是“或/“和可能的?)
Java Replace Character At Specific Position Of String?(Java替换字符串特定位置的字符?)
What is the type of a ternary expression with int and char operands?(具有 int 和 char 操作数的三元表达式的类型是什么?)
Read a text file and store every single character occurrence(读取文本文件并存储出现的每个字符)
Why do I need to explicitly cast char primitives on byte and short?(为什么我需要在 byte 和 short 上显式转换 char 原语?)