1

How can I divide a sentence like "He and his brother, are playing football." into few part like "He" , "He and", "and his", "his brother", "brother, ",", are", "brother playing" , "playing football", "football." and ".". Is it possible to do that by using 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));

This is the code I have done problem is "," inside the sentence must be separate with the word like "brother," must put as this "brother ," only will work. Any solution?

cchua
  • 213
  • 2
  • 6
  • 15
  • 1
    your split is pretty inconsistent, first you have `"brother, "` where you don't treat comma as a word and then you have `", are" where you do. Although it can be done, you might have to have edge cases for commas and full stops – Mateusz Kowalczyk Jun 23 '12 at 05:39
  • That sentence doesn't need a comma :-) – David Gelhar Jun 23 '12 at 05:39
  • ya I know, lets assume a sentence contains comma. – cchua Jun 23 '12 at 05:43
  • So the only thing wrong with your code is that it gives you `brother ,` instead of `brother,`? – cklab Jun 23 '12 at 05:59
  • The String in the sentence is `"He and his brother, are playing football."` then it will not get the result I want. If the string is `"He and his brother , are playing football ."` only will get the result. Any clue? – cchua Jun 23 '12 at 06:07
  • http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html See substring(...) – Josh Claxton Jun 23 '12 at 05:35

1 Answers1

0

Change this:

String[] words = "He and his brother , are playing football .".split("\\s+");

to:

String[] words = "He and his brother , are playing football .".split("[\\s+,]");

This will take care of the , , that is, you won't get brother,, instead you will only get brother. It will split on the occurence of a comma too.

Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108
  • but the result is not get what I want to. the `,` is missing. – cchua Jun 23 '12 at 08:16
  • You probably want to preserve the delimiters. Have a look at this : http://stackoverflow.com/questions/275768/is-there-a-way-to-split-strings-with-string-split-and-include-the-delimiters – Kazekage Gaara Jun 23 '12 at 08:31
  • `String[] words = "He and his brother, are playing football.".split("(?!^)\\b"); 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));}` I cant get the result I want to? any problem with my code – cchua Jun 23 '12 at 08:46