How can you split a word to its constituent letters?
Example of code which is not working
class Test {
public static void main( String[] args) {
String[] result = "Stack Me 123 Heppa1 oeu".split("\\a");
// output should be
// S
// t
// a
// c
// k
// M
// e
// H
// e
// ...
for ( int x=0; x<result.length; x++) {
System.out.println(result[x] + "\n");
}
}
}
The problem seems to be in the character \\a
.
It should be a [A-Za-z].
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
The string split() method breaks a given string around matches of the given regular expression. After splitting against the given regular expression, this method returns a string array.
Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.
You need to use split("");
.
That will split it by every character.
However I think it would be better to iterate over a String
's characters like so:
for (int i = 0;i < str.length(); i++){
System.out.println(str.charAt(i));
}
It is unnecessary to create another copy of your String
in a different form.
"Stack Me 123 Heppa1 oeu".toCharArray()
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With