Java > Warmup-2 > stringYak (CodingBat Solution)

Problem:

Suppose the string "yak" is unlucky. Given a string, return a version where all the "yak" are removed, but the "a" can be any char. The "yak" strings will not overlap.

stringYak("yakpak") → "pak"
stringYak("pakyak") → "pak"
stringYak("yak123ya") → "123ya"


Solution:

public String stringYak(String str) {
  String result = "";
  
  for (int i=0; i<str.length(); i++) {
    if (i+2<str.length() && str.charAt(i)=='y' && str.charAt(i+2)=='k') {
      i =  i + 2;
    } else {
      result = result + str.charAt(i);
    }
  }
  
  return result;
}

8 comments:

  1. public String stringYak(String str) {
    if(str.contains("yak")){
    return str.replace("yak","");
    }
    return str;
    }

    ReplyDelete
    Replies
    1. This is the beauty way you have return it. I am a beginner and I understood it clearly how to think and write in shortcut.

      Delete
    2. Wrong code. The a can be anything.

      Delete
    3. yes but the requirement says the middle char , 'a', can be any character so your solution is one dimensional.

      Delete
  2. Easiest way:
    public String stringYak(String str) {
    return str.replaceAll("y.k", ""); // The dot (.) means ‘any char’
    }

    ReplyDelete
  3. String [] b=str.split("yak");
    for (String s:b
    ) {
    System.out.println(s);
    }
    use in intidea

    ReplyDelete
    Replies
    1. public String stringYak(String str) {
      String res="";
      String[] sb = str.split("yak");
      for(String s: sb){
      res = res+s;
      }
      return res;
      }

      Delete