The split() method in Java does not work on a dot (.)

Bhavesh picture Bhavesh · Oct 29, 2011 · Viewed 178k times · Source

I have prepared a simple code snippet in order to separate the erroneous portion from my web application.

public class Main {

    public static void main(String[] args) throws IOException {
        System.out.print("\nEnter a string:->");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String temp = br.readLine();

        String words[] = temp.split(".");

        for (int i = 0; i < words.length; i++) {
            System.out.println(words[i] + "\n");
        }
    }
}

I have tested it while building a web application JSF. I just want to know why in the above code temp.split(".") does not work. The statement,

System.out.println(words[i]+"\n"); 

displays nothing on the console means that it doesn't go through the loop. When I change the argument of the temp.split() method to other characters, It works just fine as usual. What might be the problem?

Answer

rob mayoff picture rob mayoff · Oct 29, 2011

java.lang.String.split splits on regular expressions, and . in a regular expression means "any character".

Try temp.split("\\.").