.indexOf selective replacements
I have a StringBuffer named "sentence." I need to replace all occurrences of "A", except occurrences of "A" at the end of a word, with "E".
Example: ABABA ---> EBEBA
However, my code returns EBEBE.
Code :
while (sentence.indexOf("A") >= 0 && sentence.indexOf("A") != sentence.indexOf("A ") && sentence.indexOf("A") != sentence.indexOf("A."))
{
int AStart = sentence.indexOf("A");
int AEnd = AStart + "A".length();
sentence.replace(AStart, AEnd, "E");
}
Re: .indexOf selective replacements
Is the problem that the code replaces the last "A" with an "E"?
Add an if test to see where the location is and don't replace if it is at the end.
Re: .indexOf selective replacements
Well, why not just check if sentence.indexOf("A")==sentence.length()-1?
That statement says: if the index of A is the last index
The reason it says that is because sentence.length() returns the length of the StringBuffer, while sentence.length()-1 returns the last index of the StringBuffer.