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 count =0;
  if (str.length() ==1 && str.charAt(0) == 'h')
  count = 0;
  else
  {
  for(int i = 0;i<str.length();i++) {
    if ( (str.charAt(i) == 'h') && (str.charAt(i+1) == 'i') )
     count+=1; 
     }
     }
     return count;
}


4 comments :

  1. public int countHi(String str) {
    int count = 0;
    for(int i=0; i<str.length()-1; i++){
    if(str.charAt(i) == 'h' && str.charAt(i+1) == 'i')
    count++;
    }
    return count;
    }

    ReplyDelete
  2. int count = 0;
    for (int i = 0; i < str.length() - 1; i++){
    if (str.charAt(i) == 'h' && str.charAt(i + 1)== 'i')
    count += 1;
    }
    return count;

    ReplyDelete
  3. public int countHi(String str) {
    int count = 0;
    for (int i=0; i<str.length(); i++){
    if (str.substring(i).startsWith("hi")) count++;
    }return count;
    }

    ReplyDelete
  4. public int countHi(String str) {
    String found = "hi";
    int full = str.length();
    str = str.replace(found, "");
    int cut = str.length();
    return (full - cut) / found.length();
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact