Java word count program

后端 未结 22 1532
北荒
北荒 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:27

    public static int CountWords(String str){
    
       if(str.length() == 0)
              return 0;
    
       int count =0;
       for(int i=0;i< str.length();i++){
    
    
          if(str(i) == ' ')
              continue;
    
          if(i > 0 && str.charAt(i-1) == ' '){
            count++;
          } 
    
          else if(i==0 && str.charAt(i) != ' '){
           count++;
          }
    
    
       }
       return count;
    
    }
    

提交回复
热议问题