JavaDevNotes.com

Java String Split Count Examples

The String.split() method splits a String into an array of substrings given a specific delimiter. Here are examples on how to know the number of substring created from the split.

Count Example

Here is a simple example on how to count the number of resulting substrings given that a delimiter is the comma sign:

public static void main(String[] args) {
   String sampleString = "Cat,Dog,Elephant";
   String[] items = sampleString.split(",");
   int itemCount = items.length;
   System.out.println("The number of items is: " + itemCount);
}

Since the result of the String function is an String array, we can just invoke the length of the array to get the count that we wanted. In this case, the answer is derived from the expression items.length. This is the simplest way of getting a Java String Split's Count of substrings.

Here is the sample output as there are 3 strings separated by comma.

The number of items is: 3

Here is a shortened example:

public static void main(String[] args) {
   String sampleString = "Cat,Dog,Elephant";
   int itemCount = sampleString.split(",").length;
   System.out.println("The number of items is: " + itemCount);
}

Count Words Example

We can also use the same idea when we wish to count the number of words in a given String. For example, we are parsing a large text document.

The trick is by using whitespace as the proper delimiter. Here is an example:

public static void main(String[] args) {
   String sampleSentence = "The quick     brown\tfox\njumps\n\nover the\tlazy\r\ndog";
   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);
   }
}

Whitespace characters are the following: tab, space, and line feed. In regular expression, \s stands for a whitespace. A sequence of one or more whitespaces can be expressed as \s+. We just need to scape \ when we use in Java. Hence the code sampleSentence.split("\\s+")

Here is the output of the code:

The number of words is: 9
The
quick
brown
fox
jumps
over
the
lazy
dog

String Tutorials And Examples