如何将以下单词拆分为数组
That's the code
成
array
0 That
1 s
2 the
3 code
Run Code Online (Sandbox Code Playgroud)
我试过这样的事
String str = "That's the code";
String[] strs = str.split("\\'");
for (String sstr : strs) {
System.out.println(sstr);
}
Run Code Online (Sandbox Code Playgroud)
但输出是
That
s the code
Run Code Online (Sandbox Code Playgroud)
Kev*_*sox 16
要专门分割白色空间和撇号:
public class Split {
public static void main(String[] args) {
String [] tokens = "That's the code".split("[\\s']");
for(String s:tokens){
System.out.println(s);
}
}
}
Run Code Online (Sandbox Code Playgroud)
或拆分任何非单词字符:
public class Split {
public static void main(String[] args) {
String [] tokens = "That's the code".split("[\\W]");
for(String s:tokens){
System.out.println(s);
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您的字符串包含重音字母,我发现按单词分割的最佳解决方案是:
\n\nString[] listeMots = phrase.split("\\\\P{L}+");\nRun Code Online (Sandbox Code Playgroud)\n\n例如,如果您的字符串是
\n\nString phrase = "Salut mon homme, comment \xc3\xa7a va aujourd\'hui? Ce sera No\xc3\xabl puis P\xc3\xa2ques bient\xc3\xb4t.";\nRun Code Online (Sandbox Code Playgroud)\n\n然后您将得到以下单词(为了清晰起见,用引号括起来并用逗号分隔):
\n\n"Salut", "mon", "homme", "comment", "\xc3\xa7a", "va", "aujourd", "hui", "Ce", \n"sera", "No\xc3\xabl", "puis", "P\xc3\xa2ques", "bient\xc3\xb4t".\nRun Code Online (Sandbox Code Playgroud)\n\n希望这可以帮助!
\n