Remove a character from a string in java

1

I hope you can help me I have a java fix and I want to remove a character that is different from "a" or "b" and update the string. For example: if an aa9b comes to take away the 9 and assign it the value aab or if it comes to ababa8abaa to remove the 8 I have a variable that runs the chain one by one because there can be two invalid characters for example ab2aba8 and should remove the 2 and then the 8 . What I have is something like this:

if (((string.charAt (index))! = 'a') & ((string.charAt (index)! = 'b'))) {

// Within this if I need to update to "string" in the "index" position.

}

I already tried with string = string.substring (0, index); but I cut the string until I found the first non-valid character. For example with aaaa @ aa leaves the string string as aaaa removing the last two letters a.

I hope you can help me, thank you.

    
asked by Israel Gutierrez 14.10.2018 в 17:45
source

1 answer

2
  

Remove a character from a string in java

You can use the replaceAll() method, which replaces each substring of the string that matches the regular expression given by a replacement sequence, and returns a String

Example so you can understand better ..

String cadena = "ab87ba93abb";
System.out.println("Cadena: " + cadena.replaceAll("[^a-b]", ""));

Result: Cadena: abbaabb

The regular expression that I passed as a parameter, replaces everything that is not a or b with an empty string .

    
answered by 14.10.2018 в 18:14