I have a char array:
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?
I have a char array:
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?
No, that solution is absolutely correct and very minimal.
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 char
s and join them back is not required in normal code.
Compare this to C/C++ where "foo"
you have a bundle of char
s terminated by a zero byte on one side and string
on the other side and many conversions between them due do legacy methods.
String str = "wwwwww3333dfevvv";
char[] c = str.toCharArray();
Now to convert character array into String , there are two ways.
Arrays.toString(c);
Returns the string [w, w, w, w, w, w, 3, 3, 3, 3, d, f, e, v, v, v]
.
And:
String.valueOf(c)
Returns the string wwwwww3333dfevvv
.
In Summary: pay attention to Arrays.toString(c)
, because you'll get "[w, w, w, w, w, w, 3, 3, 3, 3, d, f, e, v, v, v]"
instead of "wwwwww3333dfevvv"
.
A String in java is merely an object around an array of chars. Hence a
char[]
is identical to an unboxed String with the same characters. By creating a new String from your array of characters
new String(char[])
you are essentially telling the compiler to autobox a String object around your array of characters.
You can use String.valueOf
method.
For example,
char[] a = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
String b = String.valueOf(a);
System.out.println("Char Array back to String is: " + b);
For more on char array to string you can refer links below
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
https://www.flowerbrackets.com/convert-char-array-to-string-java/
package naresh.java;
public class TestDoubleString {
public static void main(String args[]){
String str="abbcccddef";
char charArray[]=str.toCharArray();
int len=charArray.length;
for(int i=0;i<len;i++){
//if i th one and i+1 th character are same then update the charArray
try{
if(charArray[i]==charArray[i+1]){
charArray[i]='0';
}}
catch(Exception e){
System.out.println("Exception");
}
}//finally printing final character string
for(int k=0;k<charArray.length;k++){
if(charArray[k]!='0'){
System.out.println(charArray[k]);
} }
}
}
//Given Character Array
char[] a = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
//Converting Character Array to String using String funtion
System.out.println(String.valueOf(a));
//OUTPUT : hello world
Converting any given Array type to String using Java 8 Stream function
String stringValue =
Arrays.stream(new char[][]{a}).map(String::valueOf).collect(Collectors.joining());