Splitting words into letters in Java

How can you break a word into its constituent letters?

Sample code that doesn't work

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 is the \\a . It should be [A-Za-z].

+14
java split
05 Oct '09 at 19:26
source share
7 answers

You need to use split(""); .

This will divide it into each character.

However, I think it would be better to iterate over the String characters like this:

 for (int i = 0;i < str.length(); i++){ System.out.println(str.charAt(i)); } 

There is no need to create another copy of your String in another form.

+41
Oct 05 '09 at 19:28
source share
— -

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

+25
05 Oct '09 at 19:28
source share

Including numbers, but not spaces:

"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 spaces:

"Stack Me 123 Heppa1 oeu".replaceAll("[^az^AZ]","").toCharArray()

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

+6
05 Oct '09 at 19:45
source share
  char[] result = "Stack Me 123 Heppa1 oeu".toCharArray(); 
+3
Oct 05 '09 at 19:29
source share

you can use

 String [] strArr = Str.split(""); 
+3
Dec 07 '15 at 16:17
source share

I am sure that he does not want to display spaces.

 for (char c: s.toCharArray()) { if (isAlpha(c)) { System.out.println(c); } } 
+2
Oct 05 '09 at 19:34
source share
 String[] result = "Stack Me 123 Heppa1 oeu".split("**(?<=\\G.{1})**"); System.out.println(java.util.Arrays.toString(result)); 
+1
Jul 01 '11 at 10:19
source share



All Articles