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:
public class StringSplit {
public static void 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]);
}
}
Comments
Post a Comment