I essentially want to split up a string based on the sentences, therefore (for the sake of what I'm doing), whenever there is a !
, .
, ?
, :
, ;
.
How would I achieve this with multiple items to split the array with?
Thanks!
Using String. split() Method. The split() method of the String class is used to split a string into an array of String objects based on the specified delimiter that matches the regular expression.
To split a string with multiple delimiters:Use the str. replace() method to replace the first delimiter with the second. Use the str. split() method to split the string by the second delimiter.
In order to break String into tokens, you need to create a StringTokenizer object and provide a delimiter for splitting strings into tokens. You can pass multiple delimiters e.g. you can break String into tokens by, and: at the same time. If you don't provide any delimiter then by default it will use white-space.
The split method can be passed a regular expression containing multiple characters to split the string with multiple separators.
Guava's Splitter
is a bit more predictable than String.split()
.
Iterable<String> results = Splitter.on(CharMatcher.anyOf("!.?:;"))
.trimResults() // only if you need it
.omitEmptyStrings() // only if you need it
.split(string);
and then you can use Iterables.toArray
or Lists.newArrayList
to wrap the output results how you like.
String.split
takes a regex to split on, so you can simply:
mystring.split("[!.?:;]");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With