How to use replace(char, char) to replace all instances of character b with nothing

There's also a replaceAll function that uses strings, note however that it evals them as regexes, but for replacing a single char will do just fine.

Here's an example:

String meal = "Hambbburger";

String replaced = meal.replaceAll("b","");

Note that the replaced variable is necessary since replaceAll doesn't change the string in place but creates a new one with the replacement (String is immutable in java).

If the character you want to replace has a different meaning in a regex (e.g. the . char will match any char, not a dot) you'll need to quote the first parameter like this:

String meal = "Ham.bur.ger";

String replaced = meal.replaceAll(Pattern.quote("."),"");

Strings are immutable, so make sure you assign the result to a string.

String str = "Hambbburger";
str = str.replace("b", "");

You don't need replaceAll if you use Java 6. See here: replace


Try this code....

public class main {
public static void main(String args[]){
    String g="Hambbburger.i want to eat Hambbburger. ";
    System.out.print(g);
    g=g.replaceAll("b", "");



      System.out.print("---------After Replacement-----\n");
      System.out.print(g);

}
}

output

Hambbburger.i want to eat Hambbburger. ---------After Replacement----- Hamurger.i want to eat Hamurger.

Tags:

Java

Replace