Welcome to my blog, hope you enjoy reading
RSS

Friday 11 January 2013

How to use Java String.split method to split a string by dot


How to use Java String.split method to split a string by dot?

In java, string.split(".") does not work for splitting a string with dot (e.g.,http://javanotes2all.blogspot.in/) and will give you an array with zero element.



The Sting split(String regex) method wants a regular expression as its parameter. It splits this string around matches of the given regular expression. The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.
In regular expression, the "." is a metacharacter with special meaning which matches any single character except a newline. You got an array with zero element because "." mataches any charachers in your string.
A preceding backslash ("\") turns a metachacter into a literal character. Because this is also the Java escape character in strings, you need to use "\\" to present the backslash character. To split a string with a literal '.' character in Java, you must use split("\\."). For example,
String domain = “http://javanotes2all.blogspot.in/”;
String[] strArray = domain.split(“\\.”);
for (String str : strArray) {
System.out.println(str);
}

0 comments: