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

编程入门 行业动态 更新时间:2024-10-15 14:16:55

如何将char<a href=https://www.elefans.com/category/jswz/34/1771288.html style=数组转换回字符串?"/>

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

本文翻译自:How to convert a char array back to a string?

I have a char array: 我有一个char数组:

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

My current solution is to do 我目前的解决方案是做

String b = new String(a);

But surely there is a better way of doing this? 但肯定有更好的方法吗?


#1楼

参考:


#2楼

This will convert char array back to string: 这会将char数组转换回字符串:

char[] charArray = {'a', 'b', 'c'};
String str = String.valueOf(charArray);

#3楼

另一种方法是:

String b = a + "";

#4楼

You can also use StringBuilder class 您还可以使用StringBuilder类

String b = new StringBuilder(a).toString();

Use of String or StringBuilder varies with your method requirements. String或StringBuilder的使用因方法要求而异。


#5楼

A String in java is merely an object around an array of chars. java中的String只是一个字符数组周围的对象。 Hence a 因此a

char[]

is identical to an unboxed String with the same characters. 与具有相同字符的未装箱字符串相同。 By creating a new String from your array of characters 通过从您的字符数组创建一个新的String

new String(char[])

you are essentially telling the compiler to autobox a String object around your array of characters. 你基本上是在告诉编译器在你的字符数组周围自动放置一个String对象。


#6楼

Try this: 试试这个:

CharSequence[] charArray = {"a","b","c"};for (int i = 0; i < charArray.length; i++){String str = charArray.toString().join("", charArray[i]);System.out.print(str);
}

更多推荐

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

本文发布于:2024-03-23 16:53:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1740559.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字符串   如何将   char

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!