用Java将单词拆分为字母
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1521921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Splitting words into letters in Java
提问by Léo Léopold Hertz ??
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].
问题似乎出在性格上\\a
。它应该是 [A-Za-z]。
采纳答案by jjnguy
You need to use split("");
.
您需要使用split("");
.
That will split it by every character.
这将按每个字符拆分它。
However I think it would be better to iterate over a String
's characters like so:
但是我认为最String
好像这样迭代 a的字符:
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.
没有必要以String
不同的形式创建另一个副本。
回答by Zed
"Stack Me 123 Heppa1 oeu".toCharArray()
?
"Stack Me 123 Heppa1 oeu".toCharArray()
?
回答by Dave
char[] result = "Stack Me 123 Heppa1 oeu".toCharArray();
回答by Gandalf
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);
}
}
回答by p3t0r
Including numbers but not whitespace:
包括数字但不包括空格:
"Stack Me 123 Heppa1 oeu".replaceAll("\\W","").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
=> 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()
"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
=> S, t, a, c, k, M, e, H, e, p, p, a, o, e, u
回答by shiva krishna komuravelly
String[] result = "Stack Me 123 Heppa1 oeu".split("**(?<=\G.{1})**");
System.out.println(java.util.Arrays.toString(result));
回答by shiva krishna komuravelly
You can use
您可以使用
String [] strArr = Str.split("");