Java String to Array Splitting

时间:2016-04-13 09:49:06

标签: java split

我有一个字符串,例如:"My brother, John, is a handsome man."

我想将其拆分为数组,输出为:

"My" , "brother", "," , "John", "," , "is", "a", "handsome", "man", "."

任何人都可以帮我吗?我需要在Java上这样做。

3 个答案:

答案 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
.
相关问题