How to use replace() for the last occurrence?

Asked

Viewed 2,212 times

4

The method String#replaceFirst() is used to replace the first occurrence of a substring in a string, but how should I proceed if I want to do this with the last occurrence?

The doubt is as follows how I will make the condition to analyze the string and if you find word use the methods shown.

Here deletes last character typed.

    texto = txtTexto.getText().toString();
        int length = texto.length();  
         txtTexto.setText(texto.substring(0, length-1));

Here analyzes condition to erase an entire word.

if (texto.substring(length-3, length).equals("sin")){

    txtTexto.setText(replaceLast(texto, "sin", ""));   
    }
    else if if (texto.substring(length-4, length).equals("asin")){

    txtTexto.setText(replaceLast(texto, "asin", ""));
    }

This way it works in the sin, but when it falls into the other condition eliminates the sin and maintains the to on the screen, if you reverse the order the condition of the sin works the Asin so smaller characters, type 2 characters do not work.

  • http://answall.com/help/mcve

3 answers

4

There is a ready-made solution in that reply in the OS:

public static String replaceLast(string text, string source, string target) {
    StringBuilder b = new StringBuilder(text);
    b.replace(text.lastIndexOf(source), text.lastIndexOf(source) + source.length(), target);
    return b.toString();
}

In the same question has another answer that uses Regex and is even more suitable as the replaceFirst():

public static String replaceLast(String text, String regex, String replacement) {
    return text.replaceFirst("(?s)(.*)" + regex, "$1" + replacement);
}

I put in the Github for future reference.

  • 1

    I have no way to see if everything is as you want because the question does not contain more details, there is a code with an example of how it should be tested and the expected result. If you improve the question, I can improve the answer.

  • look at the edited question.

  • @Rodolfo but with what are you testing? What is the value of texto. Maybe what you want is not a replaceLast(), your question clearly asked for it and the two answers gave you this.

  • text is a String, is the following fit asking another question to know if it is right what I am doing just put the replaceLast not this solution needs a condition

  • @Rodolfo unfortunately I am not understand what you are writing, your text is very confusing. Try to be clearer so I can help you. And do what I told you. Here is the question to show how we can test the problem you are facing. For me, it’s all right, you have to show what’s wrong. Anyway, the question asked has been answered, we’re just trying to help with your other problem, which may require another question to be opened.

  • @bigown, I believe he is wanting to check whether the text contains a certain word, to then replace it.

  • @array may be, if it is, the problem is completely different and then the original question has already been answered and for the other problem needs a new question.

Show 2 more comments

1


Another alternative would be to use the method String#substring():

public static String replaceLast(String texto, String substituir, String substituto) {
    // Retorna o índice da última ocorrência de "substituir"
    int pos = texto.lastIndexOf(substituir); 
    // Se encontrar o índice
    if (pos > -1) { 
       // Retorna os caracteres antecedentes de "substituir"
       return texto.substring(0, pos) 
        + substituto
        // Retorna os caracteres posteriores a "substituir"
        + texto.substring(pos + substituir.length(), texto.length()); 
    } else 
       // Se a palavra especificada em "substituir" não for encontrada não altera nada
       return texto;
}

Example of use:

public static void main (String[] args) throws java.lang.Exception
{
    System.out.println(replaceLast("foobarfoobar", "foo", "")); // foobarbar
}

Response based in that OS response.

  • 1

    @What do you mean? if you want to replace the last asin just specify it in the second function parameter.

  • look at the edited question.

  • 1

    @Rodolfo See if it’s that what you want to do.

1

Even though I have two answers that "solve your problem", I will try to leave one to complement and solve your error once and for all.

String[] toRemove = {"sin", "asin", "whatever_you_want", "hi"};

for (String isRemovable : toRemove){
    if (textTexto.contains(isRemovable){
        txtTexto.setText(replaceLast(texto, isRemovable, ""));
        break;
    } else {
        // code
    }
}

With this, the code will check whether your EditText contains one of the words present in toRemove. If yes, the word will be removed.

Browser other questions tagged

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