Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting words into letters in Java [duplicate]

Tags:

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].

like image 767
Léo Léopold Hertz 준영 Avatar asked Oct 05 '09 19:10

Léo Léopold Hertz 준영


People also ask

How do I separate words from a string?

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.

How do you break down a string in Java?

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.

How do you split a string into characters?

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.


2 Answers

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.

like image 132
jjnguy Avatar answered Sep 22 '22 13:09

jjnguy


"Stack Me 123 Heppa1 oeu".toCharArray() ?

like image 29
Zed Avatar answered Sep 21 '22 13:09

Zed