Grails Cookbook - A collection of tutorials and examples

Java String Split Dot Or Period

In some cases, we use a dot or period as delimeters in order to split a string. This topic will teach the programmers on how to split a string using a dot symbol. Observe the given examples below for a better reference.

Proper Split Using Dot Or Period

Now that we know dots or periods have a special meaning to regular expressions in Java, the only proper way to split a string is through escaping using the \ character.
public class ProperSplitSample {
   public static void main(String[] args) {
      String givenSampleString = "C .  A .   T";
      String[] items = givenSampleString.split("\\.");
      int indexItem = 1;
      for (String item : items) {
         System.out.println(indexItem + ". " + item);
         indexItem++;
      }
   }
}
Check out the result below:
1. C 
2.   A 
3.    T
Observe that the printed output shows untrimmed and with spaces results. Let's try the next example with completely different output that results with untrimmed and improper split strings.

Improper Split Using Dot Or Period

Take a look at this example, considering we have the String "C . A . T", passing the period or dot straight to the split method of Java String, we should conclude that this process is incorrect.
public class ImroperSplitSample {
   public static void main(String[] args) {
      String givenSampleString = "C .  A .   T";
      String[] items = givenSampleString.split(".");
      int indexItem = 1;
      for (String item : items) {
         System.out.println(indexItem + ". " + item);
         indexItem++;
      }
   }
}
Note that the program above will show nothing, the reason behind this is because dots or periods have meaning to regular expressions.

Trimmed Split String Using Dot Or Period

Observe the written program below, understand the process on how to trim the both sides of the split string using dots or periods.
public class TrimmedSplitSample {
   public static void main(String[] args) {
      String givenSampleString = "C .  A .   T";
      String[] items = sampleString.split("\\s*\\.\\s*");
      int indexItem = 1;
      for (String item : items) {
         System.out.println(indexItem + ". " + item);
         indexItem++;
      }
   }
}
Notice that we've altered the regular expression ( \.), and appended a sequence of zero or white spaces (\s*) on both sides of the split string to get the resulting value. Check the output of the program below:
1. C
2. A
3. T
The result shows trimmed and equally balanced on both sides using white spaces, making it polished and clean.