我有一个字符串,例如:"My brother, John, is a handsome man."
我想将其拆分为数组,输出为:
"My" , "brother", "," , "John", "," , "is", "a", "handsome", "man", "."
任何人都可以帮我吗?我需要在Java上这样做。
答案 0 :(得分:5)
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
.
答案 1 :(得分:0)
如果您只考虑,
和.
,那么方法将使用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" "."
答案 2 :(得分:0)
试试这个。
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
.