Quantcast
Channel: Techie Shah
Viewing all articles
Browse latest Browse all 25

Java: How to split a string based on . (DOT) , (COMMA) : (COLON)

$
0
0

In Java language, DOT is a special character in the regular expression. If you have the following string

String str = "He is a boy. He is my friend";

The following statement will return an empty string array

String tokens[] = s.split(".");

Solution:

You can split a string based on DOT in the following two ways

a) String tokens[] = str.split("[.]");

b) String tokens[] = str.split("\\.");


The same solution also applies to the following characters

a) WHITE SPACE 

b) COMMA

c) COLON

Complete Example:

publicclass StringSplit {

    publicstaticvoid main(String[] args) {

        String str = "He is a boy.He is my friend";

        String tokens[] = str.split("[.]");

        System.out.println(tokens[0]);

        System.out.println(tokens[1]);


        //or using escape character

        tokens = str.split("\\.");

        System.out.println(tokens[0]);

        System.out.println(tokens[1]);

    }

}


Viewing all articles
Browse latest Browse all 25

Trending Articles