JavaDevNotes.com

Java String Split Dot Or Period Examples

There are cases when items on a Java String are separated by the dot symbol. Below are examples on how to Split a String using Dot or Period as delimiters.

Incorrect Split using Dot or Period

Say for example we have the String "A . B . C", it is not correct to pass the dot symbol directly to the split method of Java String.
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.

Proper Split using Dot or Period

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.    C

Notice that the items are not trimmed and contains spaces.

Split using Dot or Period with trim

Here is how to split a String with dots but all tokens are trimmed on both sides.
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. C
The resulting output is cleaner.

String Tutorials And Examples