tags:

views:

1085

answers:

5

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

+4  A: 

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

Zed
+1: Simple, concise, and can easily be fed to for.
R. Bemrose
Creating an extra char array is an extra step that is not necessary.
jjnguy
Depends. My _guess_ is that above a certain length an arrayCopy and direct array access is "faster" than calling hundreds of charAt's.
Zed
Calling `charAt` is O(1) because the String is implemented using an array in the back end. Creating a copy will be slower always.
jjnguy
Calling `charAt(i)` is implemented to first make a sanity check on the input parameter then offsetting it with the internal offset, and after this yes, it is an array access.
Zed
+2  A: 

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.

jjnguy
+1: Hmm, I didn't think about creating another copy of the string. Good point.
R. Bemrose
I cannot use `split("")` because I need to get only the characters [A-Za-z].
Masi
A: 
 char[] result = "Stack Me 123 Heppa1 oeu".toCharArray();
Dave
A: 

I'm pretty sure he doesn't want the spaces to be output though.

for (char c: s.toCharArray()) {
    if (isAlpha(c)) {
       System.out.println(c);
     }
}
Gandalf
+1  A: 

Including numbers but not whitespace:

"Stack Me 123 Heppa1 oeu".replaceAll("\\W","").toCharArray();

=> S, t, a, c, k, M, e, 1, 2, 3, H, e, p, p, a, 1, o, e, u

Without numbers and whitespace:

"Stack Me 123 Heppa1 oeu".replaceAll("[^a-z^A-Z]","").toCharArray()

=> S, t, a, c, k, M, e, H, e, p, p, a, o, e, u

p3t0r