How do I use replace () for the last occurrence?

4

The String#replaceFirst() method 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 question is how do I make the condition to parse the string and find word to use the methods presented.

Here it deletes the last typed character.

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

Here analyzes the condition to delete 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 works in sin , but when it falls into the other condition it deletes sin and keeps a on the screen, if you reverse the order the condition of the sin function

    
asked by anonymous 08.03.2015 / 16:43

3 answers

1

Alternatively, you could 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 usage:

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

Response based on on this SO response .

    
08.03.2015 / 17:41
4

There is a ready solution in this answer in the SO :

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 you have another answer that uses RegEx and is even more like replaceFirst() :

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

While having two answers that "solve your problem", I will try to leave one to complement and solve your mistake.

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 if your EditText contains one of the words present in toRemove . If so, the word will be removed.

    
08.03.2015 / 19:18