Java > String-3 > notReplace (CodingBat Solution)

Problem:

Given a string, return a string where every appearance of the lowercase word "is" has been replaced with "is not". The word "is" should not be immediately preceeded or followed by a letter -- so for example the "is" in "this" does not count. (Note: Character.isLetter(char) tests if a char is a letter.)

notReplace("is test") → "is not test"
notReplace("is-is") → "is not-is not"
notReplace("This is right") → "This is not right"


Solution:

public String notReplace(String str) {
  String result = "";
  int len = str.length();
  
  for(int i = 0; i < len; i++){
    if(i-1 >= 0 && Character.isLetter(str.charAt(i-1))
    || i+2 < len && Character.isLetter(str.charAt(i+2))) {
      result += str.charAt(i);
    }
    else if(i+1 < len && str.substring(i, i+2).equals("is")) {
      result += "is not";
      i++;
    }
    else result += str.charAt(i);
  }
  return result;
}

6 comments:

  1. public String notReplace(String str) {
    str=" "+str+" ";
    String s="";
    for(int i=0; i<str.length()-1; i++) {
    if(str.substring(i, i+2).equalsIgnoreCase("is")
    &&!Character.isAlphabetic(str.charAt(i-1))
    &&!Character.isAlphabetic(str.charAt(i+2))) {
    s=s+str.substring(i, i+2)+" not";
    i=i+1;
    }
    else {
    s=s+str.charAt(i);
    }
    }
    return s.trim();
    }

    ReplyDelete
  2. str = str.replace(str," " + str + " ");
    String newStr = "";
    for(int i = 0;i<str.length()-1;i++)
    {
    if(str.substring(i,i+2).equals("is"))
    {
    if(!Character.isLetter(str.charAt(i-1))&&!Character.isLetter(str.charAt(i+2))){
    newStr+="is not";
    i++;
    continue;
    }
    }
    newStr+=str.charAt(i);
    }
    return newStr.replaceAll("^\\s","");

    ReplyDelete
  3. public String notReplace(String str) {
    str = " " + str + " ";
    final StringBuilder sb = new StringBuilder();
    for(int i=0; i<str.length()-1; i++) {
    if(str.substring(i, i+2).equalsIgnoreCase("is")
    &&!Character.isAlphabetic(str.charAt(i-1))
    &&!Character.isAlphabetic(str.charAt(i+2))) {
    sb.append(str, i, i + 2).append(" not");
    i ++;
    }
    else {
    sb.append(str.charAt(i));
    }
    }
    return sb.toString().trim();
    }

    ReplyDelete
  4. Is there a way to use .replaceAll() ?

    ReplyDelete
    Replies
    1. return str.replaceAll("\\b(is)\\b", "is not");

      Delete
  5. public String notReplace(String str) {
    String result = "";
    str += " ";
    int l = str.length();
    for (int i=0; i<l-1; i++) {
    if (str.substring(i, i+2).equals("is") && (i == 0 && !Character.isLetter(str.charAt(i+2)) || i == l-2 && !Character.isLetter(str.charAt(i-1)) || !Character.isLetter(str.charAt(i+2)) && !Character.isLetter(str.charAt(i-1))))
    {
    result += "is not";
    i += 1;
    }
    else result += "" + str.charAt(i);
    }

    return result;
    }

    ReplyDelete