我有一个字符串,例如:"My brother, John, is a handsome man."
我想把它拆分成一个数组,这样输出就是:
"My" , "brother", "," , "John", "," , "is", "a", "handsome", "man", "."有人能帮我吗?我需要在Java上做到这一点。
发布于 2016-04-13 17:57:20
replaceAll()和split()的组合应该可以做到这一点。
public static void main(String[] args) {
String s ="My brother, John, is a handsome man.";
s = s.replaceAll("(\\w+)([^\\s\\w]+)", "$1 $2"); // replace "word"+"punctuation" with "word" + <space> + "punctuation"
String[] arr = s.split("\\s+"); // split based on one or more spaces.
for (String str : arr)
System.out.println(str);
}O/P:
My
brother
,
John
,
is
a
handsome
man
.发布于 2016-04-13 18:01:43
如果只考虑,和.,那么一种方法是使用replace()和split()
String x = "My brother, John, is a handsome man.";
String[] s = x.replace(",", " ,").replace(".", " .").split("\\s+");
for (String str : s)
System.out.print("\"" + str + "\"" + " ");输出:
"My" "brother" "," "John" "," "is" "a" "handsome" "man" "." 发布于 2016-04-13 18:15:37
尝尝这个。
String string = "My brother, John, is a handsome man.";
for (String s : string.split("\\s+|(?=[.,])"))
System.out.println(s);结果是
My
brother
,
John
,
is
a
handsome
man
.https://stackoverflow.com/questions/36594656
复制相似问题