1

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?

Jack
  • 131
  • 1
  • 3
  • 13
  • Does the input always come with periods like that? – takendarkk Feb 27 '14 at 03:56
  • possible duplicate of [Java: remove all occurances of char from string](http://stackoverflow.com/questions/4576352/java-remove-all-occurances-of-char-from-string) – Blue Ice Feb 27 '14 at 03:56

4 Answers4

5

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*");
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • Use \s* to check for multiple spaces – Mason T. Feb 27 '14 at 04:03
  • Although this is no longer wrong on the example input, it was just a single example. OP asked "I would like for periods to be ignored during the split." I don't see how this fits that requirement. For example, what about a sentence with an ellipsis... – mbroshi Feb 27 '14 at 04:04
  • @mbroshi Couldn't you just then add a `+` after the `.`? – Sotirios Delimanolis Feb 27 '14 at 04:05
  • I suppose this has become a nearly Talmudic discussion at this point. I will remove my downvote and let the OP sort things out him/herself. – mbroshi Feb 27 '14 at 04:10
  • @user2310289 Thanks for the updated answers and explanation of regular expressions. – Jack Feb 27 '14 at 22:58
1
String[] test = testString.split("\\.\\s*");
Mason T.
  • 1,567
  • 1
  • 14
  • 33
0

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(".",""));
      }}
Nambi
  • 11,944
  • 3
  • 37
  • 49
0
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);
        }
    }
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331