Java word count program

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

    Not sure if there is a drawback, but this worked for me...

        Scanner input = new Scanner(System.in);
        String userInput = input.nextLine();
        String trimmed = userInput.trim();
        int count = 1;
    
        for (int i = 0; i < trimmed.length(); i++) {
          if ((trimmed.charAt(i) == ' ') && (trimmed.charAt(i-1) != ' ')) {
            count++;
          }
        }
    

提交回复
热议问题