How to transform a String "Caiaaaque" to another String "Kayak"?

3

I'm developing a system where the user types a wrong word, and I changed one or another letter of that word to correct, just for the same study purposes, and I have to go through the whole String and take an example, the user type Caiaaaque and I have to go through this letter-by-letter string and replace the error with the correct 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' getting thus Cique. And I want to return to Kayak.

    
asked by anonymous 24.09.2015 / 21:25

1 answer

2

The replaceFirst was meant to be used with regular expressions, not with strings, let alone with 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 really want to work with regular expressions [1].

So, my suggestion is to avoid replacements, but to use the #

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

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

    Example .

        
  • 24.09.2015 / 22:29