Java > String-2 > countHi (CodingBat Solution)

Problem:

Return the number of times that the string "hi" appears anywhere in the given string.

countHi("abc hi ho") → 1
countHi("ABChi hi") → 2
countHi("hihi") → 2


Solution:

public int countHi(String str) {
  int len = str.length();
  int count = 0;
  
  for (int i = 0; i < len - 1; i++) {
    String temp = str.substring(i, i+2);
    if (temp.compareTo("hi") == 0)
      count++;  
  }
  return count;
}

No comments:

Post a Comment