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 chars and join them back is not required in normal code.
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.
Assigning a String to a Char array
Converting String to "Character" array in Java - Stack Overflow
Why stream don't have char[]?
Convert a word into a char array
Videos
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 chars and join them back is not required in normal code.
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.
String text = String.copyValueOf(data);
or
String text = String.valueOf(data);
is arguably better (encapsulates the new String call).
So what I am trying to do is to input String and then assign each letter to a Char array. The problem I have is that I need to implement it in a way that no matter how long the String Java knows to assign each component of the array to the corresponding letter in the String.
My code in Java:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a first number ");
int x = scan.nextInt();
IntegerToString(x);
}
public static void IntegerToString(int x){
int numberOne = x;
System.out.println("This is the number: " + numberOne);
System.out.println("Now Backend needs to convert this number into a String");
String numberWord = Integer.toString(numberOne);
int lengthOf = numberWord.length();
char[] array = new char[lengthOf];
array[0] = numberWord.charAt(0);
array[1] = numberWord.charAt(1);
array[2] = numberWord.charAt(2);
I hope this makes sense. Thanks.
Use this:
String str = "testString";
char[] charArray = str.toCharArray();
Character[] charObjectArray = ArrayUtils.toObject(charArray);
One liner with java-8:
String str = "testString";
//[t, e, s, t, S, t, r, i, n, g]
Character[] charObjectArray =
str.chars().mapToObj(c -> (char)c).toArray(Character[]::new);
What it does is:
- get an
IntStreamof the characters (you may want to also look atcodePoints()) - map each 'character' value to
Character(you need to cast to actually say that its really achar, and then Java will box it automatically toCharacter) - get the resulting array by calling
toArray()