java – How to transform a "Kayak" String to another "Kayak" String?

Question:

I'm developing a little system where the user types a wrong word, and I changed one or another letter of that word to correct it, just for study purposes, and I have to go through the entire String and get an example, the user types Caiaaaque and I have to go through this string letter by letter and replace the error with the correct one getting Kayak.

The code snippet looks 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 types Caiaaaque, for example, he removes all the 'a', thus getting Cique. And I want to return Kayak.

Answer:

The replaceFirst method is meant to be used with regular expressions, not strings, let alone characters. For example, if you do:

String s = "a..";
s.replaceFirst("" + s.charAt(1), "");

The result will be ".." (because . is a regular expression that matches "anything"). Trying to adapt your code to do what you want is fruitless unless you actually want to work with regular expressions[1].

Therefore, my suggestion is to avoid substitutions, rather use the substring method to get the string to the point you are at and join it with the substring after the point you want to strip.


[1]: And if you want to work with regular expressions, the simplest way to do that is through backreferences (a single line of code does all the work):

palavra = palavra.replaceAll("(.)\1+", "$1");

Example .

Scroll to Top