3
I’m developing a system where the user typed a wrong word, and I changed one or another letter of this word to correct, just for the purposes of studies anyway, and I have to go through the whole String and take an example, the user type Caiaaaque and I have to go through this string letter by letter and replace the error by the correct getting Kayak.
The code part is already like this:
public String retornaPalavra(String palavra){
//for pra percorrer a String
for(int i; i<palavra.lenght()-1;i++){
if(palavra.charAt(i)==palavra.charAt(i+1)){
palavra = palavra.replaceFirst(palavra.charAt(i), '');
i = i-1;
}
}
retorno = palavra;
}
Now the problem is that if the user type Caiaaaque for example he removes all 'a' thus getting Cique. And I want to return Kayak.
Now I read that it is for study purposes. I withdrew my comment questioning the efficiency of the method.
– Piovezan
You simplified the code before posting it here, right? This section above doesn’t even compile... And even solving the build errors, it launches a
ArrayIndexOutOfBoundsException
(for you trying to access thei+1
beingi
the last index of the string. Problems of this type could be avoided with a Minimum, Complete and Verifiable Example.– mgibsonbr
@Piovezan if it is of greater efficiency tb valley
– Tiago Ferezin
@mgibsonbr yes I simplified even, qto to these errors are already being treated not to give the errors.
– Tiago Ferezin
The problem is I can’t reproduce your mistake, so I don’t know the best way to help you (except by doing it for you, which I imagine is not what you want). In ideone the result I had was "Ciaaaque".
– mgibsonbr
@mgibsonbr extly, the resulting error is not relevant, I just want to know how to replace the other 'aaa' by 'a' without interfering in the first.
– Tiago Ferezin
If the user type some google word, which is correct, you will incorrectly change it to Gogle?
– EProgrammerNotFound