Java word count program

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

    To count specified words only like John, John99, John_John and John's only. Change regex according to yourself and count the specified words only.

        public static int wordCount(String content) {
            int count = 0;
            String regex = "([a-zA-Z_’][0-9]*)+[\\s]*";     
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(content);
            while(matcher.find()) {
                count++;
                System.out.println(matcher.group().trim()); //If want to display the matched words
            }
            return count;
        }
    

提交回复
热议问题