public class TestConsole { public static void main(String[] args) { String sampleString = "A . B . C"; String[] items = sampleString.split("."); int itemIndex = 1; for (String item : items) { System.out.println(itemIndex + ". " + item); itemIndex++; } } }Surprisingly, this code will have no output. Nothing will be printed on the console. This is because dots have special meaning to regular expressions.
Since dot has special meaning, we can only use it by escaping with the \ character.
public class TestConsole { public static void main(String[] args) { String sampleString = "A . B . C"; String[] items = sampleString.split("\\."); int itemIndex = 1; for (String item : items) { System.out.println(itemIndex + ". " + item); itemIndex++; } } }
And there is output on the console.
1. A 2. B 3. CNotice that the items are not trimmed and contains spaces.
public class TestConsole { public static void main(String[] args) { String sampleString = "A . B . C"; String[] items = sampleString.split("\\s*\\.\\s*"); int itemIndex = 1; for (String item : items) { System.out.println(itemIndex + ". " + item); itemIndex++; } } }As you could see, I modified the regular expression ( \.) . I added a sequence of zero or more white space (\s*) both on the left and on the right.
1. A 2. B 3. CThe resulting output is cleaner.