Java word count program

后端 未结 22 1540
北荒
北荒 2020-12-09 06:48

I am trying to make a program on word count which I have partially made and it is giving the correct result but the moment I enter space or more than one space in the string

22条回答
  •  感动是毒
    2020-12-09 07:06

    public static void main (String[] args) {
    
         System.out.println("Simple Java Word Count Program");
    
         String str1 = "Today is Holdiay Day";
    
         String[] wordArray = str1.trim().split("\\s+");
         int wordCount = wordArray.length;
    
         System.out.println("Word count is = " + wordCount);
    }
    

    The ideas is to split the string into words on any whitespace character occurring any number of times. The split function of the String class returns an array containing the words as its elements. Printing the length of the array would yield the number of words in the string.

提交回复
热议问题