1

I have a String, for example : "My brother, John, is a handsome man."

I would like to split this to an array such that the output is:

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

Can anyone help me with this? I need to do this on Java.

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
Nana
  • 77
  • 1
  • 11
  • You can start with yourString.split(" "); Then you'll need a regex to separate the punctuation from the words. That should give you a starting point, see what you can find out for yourself – Draken Apr 13 '16 at 09:55
  • You have a good bunch of answers. If you want more, take a look here http://stackoverflow.com/questions/2206378/how-to-split-a-string-but-also-keep-the-delimiters – RubioRic Apr 13 '16 at 10:21

3 Answers3

5

A combination of replaceAll() and split() should do it.

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
.
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

If you are considering only for , and . then an approach would be using replace() and 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 + "\"" + " ");

Output:

"My" "brother" "," "John" "," "is" "a" "handsome" "man" "." 
rev_dihazum
  • 818
  • 1
  • 9
  • 19
0

Try this.

    String string = "My brother, John, is a handsome man.";
    for (String s : string.split("\\s+|(?=[.,])"))
        System.out.println(s);

result is

My
brother
,
John
,
is
a
handsome
man
.