Split string by space and ignore periods
-
23-12-2019 - |
Question
I'm trying to take in a String
as an input, split it by the space character in order to store the words in an array, and then use those words to compare to other words. The problem is I would like for periods to be ignored during the split as the words they are being compared to will never contain a period.
For example:
String testString = "This. is. a. test. string.";
String[] test = testString.split(" ");
for (int i = 0; i < test.length; i++) {
System.out.println(test[i]);
}
This will print out:
This.
is.
a.
test.
string.
Instead, I would like it to print out:
This
is
a
test
string
How can I ignore the period during the split?
Solution
How about
String[] test = testString.split("\\.[ ]*");
or
String[] test = testString.split("\\.\\s*");
or for more than one period (and ellipsis)
String[] test = testString.split("\\.+\\s*");
OTHER TIPS
String[] test = testString.split("\\.\\s*");
replace the dot inside the splitted string replace(".","");
String testString = "This. is. a. test. string.";
String[] test = testString.split(" ");
for (int i = 0; i < test.length; i++) {
System.out.println(test[i].replace(".",""));
}}
public class Main {
public static void main(String[] args) {
String st = "This. is. a. test. string."";
String[] tokens = st.split(".(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
for(String t : tokens) {
System.out.println("> "+t);
}
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow