i'm working on notreplace problem on codingbat. i've identified section of code wrong have not idea why. when notreplace("this right") called output: "thtest test right". why following section of code run?
else if (!(character.isletter(i-1)) && i+2<len && !(character.isletter(i+2))){ newstr += "test"; i++; } when i==2, charat(i-1)=='h' first condition not satisfied, since h letter 'is' still gets replaced 'test'. appreciated. full code below:
public string notreplace(string str) { string newstr = ""; string in = "is not"; int len = str.length(); (int i=0; i<len; i++){ if (str.substring(i,math.min(i+2,len)).equals("is")){ if (i==0 && i+2<len && !(character.isletter(i+2))){ newstr += in; i++; } else if (i+2==len && !(character.isletter(i-1))){ newstr += in; i++; } else if (!(character.isletter(i-1)) && i+2<len && !(character.isletter(i+2))){ newstr += "test"; i++; } else newstr += str.charat(i); } else newstr += str.charat(i); } return newstr; }
character.isletter(i - 1) when i =2 character.isletter(i-1) --> character.isletter(1)
so it's false , because 1 not letter . first condition !character.isletter(i - 1) true.you have missed charat(i-1) part
you should use
!character.isletter(charat(i-1))
Comments
Post a Comment