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; }
public String notReplace(String str) {
ReplyDeletestr=" "+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();
}
str = str.replace(str," " + str + " ");
ReplyDeleteString 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","");
public String notReplace(String str) {
ReplyDeletestr = " " + 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();
}
Is there a way to use .replaceAll() ?
ReplyDeletereturn str.replaceAll("\\b(is)\\b", "is not");
Deletepublic String notReplace(String str) {
ReplyDeleteString 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;
}