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 preceded 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"
Source
Solution:
public String notReplace(String s) {String news="";if(s.indexOf("is")==-1) return s;for(int i=0 , end=0 ; i<s.length()-1;i++){i=s.indexOf("is",i);if(i==0){if(s.length()==2) news= "is not";else if(!Character.isLetter(s.charAt(2))) {news= "is not";end=i=2;}}else if(i== s.length()-2){if(!Character.isLetter(s.charAt(i-1)))news+= s.substring(end,i)+"is not";elsenews+= s.substring(end);}else if(i==-1){// no more 'is' snews+= s.substring(end);break;}else{if(!Character.isLetter(s.charAt(i-1))&&!Character.isLetter(s.charAt(i+2))){news+= s.substring(end,i)+"is not";end=i=i+2;}}}return news;}
jegadeesh · 432 weeks ago
final StringBuilder sb = new StringBuilder()
.append(' ').append(str).append(" ");
for (int i = 0; i < sb.length() - 2; i++) {
if (!Character.isLetter(sb.charAt(i)) &&
sb.charAt(i + 1) == 'i' &&
sb.charAt(i + 2) == 's' &&
!Character.isLetter(sb.charAt(i + 3))) {
sb.insert(i + 3, " not");
i += 5;
}
}
return sb.substring(1, sb.length() - 1);
}