0

I am working with strings and had a quick question. I have a string of text I extracted from a file and now want to create a string array with each sentence of the text, I understand I could use string.split("."); for periods but how do I add question marks and exclamation marks. I tried string.split("." + "!" + "?"); but that didn't seem to work. Any help would be appreciated!

Java Devil
  • 10,629
  • 7
  • 33
  • 48

1 Answers1

3

string.split(".") does not work as you expect it does...

String s = "Hello.world";
System.out.println(Arrays.toString(s.split("."))); // outputs [] 

Split method takes a regex.

String s = "Hello.world";
System.out.println(Arrays.toString(s.split("\\."))); // outputs [Hello, world]

The regex of ".!?" says "any character followed by zero or more !" (which effectively is the same result as just ".")

If you want to split on individual characters, use a character class

string.split("[.!?]")

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245