[Solved] I’m trying to make a method that counts the total number of words in an array without the spaces [closed]


In this scenario, the string has to split by spaces and it will give an array of both words and empty spaces. The next step will be to count the non-empty words, so for that we need to iterate the array and check for non-empty words and increment the count.

You can try in this way given below:

public class WordCount {
          public static void main(String[] args) {
            String inputString = "Hello! Welcome to Kenzie.  My name is Robert, and I'm here with my friend Waldo.  Have you met waldo?";
            //Splitting the given string on the basis of empty spaces, it will give the array including
            // both words and empty spaces as well
            String[] arr = inputString.split(" ");
            int count = 0;
            //Iterating the array and checking each element whether it is empty or not
            for (String str : arr) {
              if (str != null && !str.trim().equals("")) {//This condition will increase the count only for non-empty strings and will get the proper word count in the output
                count++;
              }
            }
            System.out.println(count);
          }
        }

Output:

19

1

solved I’m trying to make a method that counts the total number of words in an array without the spaces [closed]