Java word count program

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

    Java does have StringTokenizer API and can be used for this purpose as below.

    String test = "This is a test app";
    int countOfTokens = new StringTokenizer(test).countTokens();
    System.out.println(countOfTokens);
    

    OR

    in a single line as below

    System.out.println(new StringTokenizer("This is a test app").countTokens());
    

    StringTokenizer supports multiple spaces in the input string, counting only the words trimming unnecessary spaces.

    System.out.println(new StringTokenizer("This    is    a test    app").countTokens());
    

    Above line also prints 5

提交回复
热议问题