在Java中将单词拆分成字母

你怎么能把一个单词分成它的组成字母?

代码示例不起作用

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"); } } } 

问题似乎在于角色\\a 。 它应该是[A-Za-z]。

你需要使用split("");

这会将每个角色分开。

但是我认为迭代String的字符会更好:

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

不必以其他forms创建String另一个副本。

"Stack Me 123 Heppa1 oeu".toCharArray()

包括数字但不包括空格:

"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

没有数字和空格:

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

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

  char[] result = "Stack Me 123 Heppa1 oeu".toCharArray(); 

您可以使用

 String [] strArr = Str.split(""); 

我很确定他不希望输出空格。

 for (char c: s.toCharArray()) { if (isAlpha(c)) { System.out.println(c); } } 
 String[] result = "Stack Me 123 Heppa1 oeu".split("**(?<=\\G.{1})**"); System.out.println(java.util.Arrays.toString(result));