How to count the number of words "hello" in a line in Java?

  • one
    Do you need to count the number of words , or the number of occurrences of the substring ? What is the response expected from the following lines: "hello", "hello, jack", "hello"? - VladD
  • It is the words. - romanzi
  • 2
    Here, the truth is "Hello" with a capital letter ... Pattern p = Pattern.compile ("[^ \\ p {L}] +"); String ar [] = p.split (str); for (i = 0, count = 0; i <ar.length; i ++) if (a [i] .equals ("Hello")) count ++; - alexlz
  • one
    @alexlz, it’s more efficient to search for the word “hello” itself - these are regular expressions. They can do almost everything when working with text. \\ hello \\ b with the register ignore flag. It is necessary to count the number of occurrences of this expression. - ReinRaus 7:07

3 answers 3

String str = "1100011"; int countNulls=0, countOnes = 0; for (char element : str.toCharArray()){ if (element == '0') countNulls++; if (element == '1') countOnes++; } 

Approximately this principle, only you split the sentence with the split () method, and substitute the array of received data instead of "str.toCharArray ()" and the type is not "char", but the string, you write your word "hello" in the body, it is easier than regular expressions, although I really love regulars)))

    @ReinRaus about efficiency - I agree. And so - as you wish:

      int count = 0; Pattern p = Pattern.compile("\\bПривет\\b", Pattern.UNICODE_CASE|Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(s); while(m.find()) count++; 

    Someone translated in response while he corrected the comment ...

      break the string into words and compare each word with "hello" How many times do you meet - so many occurrences of the word in the string)