Grails Cookbook - A collection of tutorials and examples

Java String Split Count

Just a reminder that the Java String.split() method is used to split a String to make an array of substrings through a specific delimeter. This topic will discuss on how the system will count the substrings created from the split method. Study and observe the written examples below:

Count Example

Study the program below on how the process works.
public class JavaStringSplitCountTestProgram {
    public static void main(String[] args) {
        //This is an example on how to count the substrings through the given delimeter which is the comma sign. 
        String sampleString = "Bird,Dog,Panda,Fish";
        String[] items = sampleString.split(",");
        int itemCount = items.length;
        System.out.println("The number of items in the list is: " + itemCount);
    }
}
Notice the expression items.length, what the program will do is it will invoke the length of the array to get the count of the susbstrings, since, the String function is a String array. The expression that we encoded is the reason we got the count of the numbers in the list.

Check out the result below:

The number of items in the list is: 4
Now let's try the same implementation but with a shorter version. Note that the output of this example will also show the same result above.
public class JavaStringSplitCountTestProgram {
    public static void main(String[] args) {
        String sampleString = "Bird,Dog,Panda,Fish";
        int itemCount = sampleString.split(",").length;
        System.out.println("The number of items in the list is: " + itemCount);
     }
}

Count Words Example

We can also repeat the procedure we did when we are parsing a large text document. Only this time, utilizing a whitespace as delimeter can be efficient and effective. Observe the sample program below:
public class JavaStringSplitCountTestProgram {
    public static void main(String[] args) {
        String sampleSentence = "Twinkle twinkle     little\tstar\nhow\n\nI wonder\twhat\r\nyou\nare";
        String[] words = sampleSentence.split("\\s+");
        int itemCount = words.length;
        System.out.println("The number of words is: " + itemCount);
        for (int i = 0; i < itemCount; i++) {
           String word = words[i];
           System.out.println(word);
        }
     }
}
Tab, space and line feed are what the Whitespace characters are made of. Understand that \s is for a whitespace. When a sequence of one or more whitespace are required, use \s+. Notice that we used \ in the program for scaping, as a result, the code sampleSentence.split("\\s+") was also utilized.

Check out the result below:

The number of words in the list is: 10
Twinkle
twinkle
little
star
how
I
wonder
what
you
are