如何将像"He and his brother, are playing football."
这样的句子分成几部分,例如"He"
,"He and"
,"and his"
,"his brother"
,"brother, "
,", are"
,"brother playing"
,"playing football"
,"football."
和"."
。使用Java可以做到吗?
String[] words = "He and his brother , are playing football .".split("\\s+");
System.out.println(words[0]);
for (int i = 0, l = words.length; i + 1 < l; i++){
System.out.println(words[i] + " " + words[i + 1]);
}
String s = words[words.length-1];
System.out.println(s.charAt(s.length() - 1));
这是我做过的代码,问题是“,”句子中的单词必须与
"brother,"
这样的单词分开,因为该"brother ,"
仅能正常工作。有什么办法吗? 最佳答案
更改此:
String[] words = "He and his brother , are playing football .".split("\\s+");
至:
String[] words = "He and his brother , are playing football .".split("[\\s+,]");
这将照顾
,
,即,您不会得到brother,
,而只会得到brother
。它也会在出现逗号时分裂。关于java - 如何将中间包含逗号的句子分成部分Java?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11167144/