Java > String-3 > countYZ (CodingBat Solution)

Problem:

Given a string, count the number of words ending in 'y' or 'z' -- so the 'y' in "heavy" and the 'z' in "fez" count, but not the 'y' in "yellow" (not case sensitive). We'll say that a y or z is at the end of a word if there is not an alphabetic letter immediately following it. (Note: Character.isLetter(char) tests if a char is an alphabetic letter.)

countYZ("fez day") → 2
countYZ("day fez") → 2
countYZ("day fyyyz") → 2


Solution:

public int countYZ(String str) {
  int len = str.length();
  int count = 0;
  str = str.toLowerCase();
  
  for (int i = 0; i < len; i++) {
    
    if (str.charAt(i) == 'y' || str.charAt(i) == 'z') {
      if (i < len-1 && !Character.isLetter(str.charAt(i+1)))
        count++;
      else if (i == len-1)
        count++;
    }
  }
  return count;
}


3 comments :

  1. public int countYZ(String str) {
    int l= str.length();
    int countYZ = 0;
    str = (str + " ").toLowerCase();

    for (int i = 0; i<=l; i++) {
    if ((str.charAt(i) == 'z' || str.charAt(i) == 'y') && !Character.isLetter(str.charAt(i+1))) countYZ ++;
    }
    return countYZ ;
    }

    ReplyDelete
  2. public int countYZ(String str) {
    str = str.toLowerCase();
    String[] wordsSet = str.split("[^a-z]");
    int result = 0;
    for (String word : wordsSet) {
    if (word.endsWith("y") || word.endsWith("z")) {
    result++;
    }
    }
    return result;
    }

    ReplyDelete
  3. public int countYZ(String str) {
    int count=0;
    str=str.toLowerCase();
    for(int i=0;i0 && !Character.isLetter(str.charAt(i))){
    if(str.charAt(i-1)=='z' || str.charAt(i-1)=='y'){
    count++;
    }
    count+=0;
    }
    if(i==str.length()-1 && (str.charAt(i)=='z' || str.charAt(i)=='y')){
    count++;
    }
    }
    return count;
    }

    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