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

Asked

Viewed 149 times

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.

  • 1

    Now I read that it is for study purposes. I withdrew my comment questioning the efficiency of the method.

  • 1

    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 the i+1 being i the last index of the string. Problems of this type could be avoided with a Minimum, Complete and Verifiable Example.

  • @Piovezan if it is of greater efficiency tb valley

  • @mgibsonbr yes I simplified even, qto to these errors are already being treated not to give the errors.

  • 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 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.

  • If the user type some google word, which is correct, you will incorrectly change it to Gogle?

Show 2 more comments

1 answer

2


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

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

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

Therefore, my suggestion is to avoid substitutions, rather to use the method substring to pick the string up to the point you are and join with the substring after the point you want to pull out.


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

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

Example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.