How do i use replace(char, char) to replace all instances of character "b" with nothing.
For example:
Hambbburger to Hamurger
EDIT: Constraint is only JDK 1.4.2, meaning no overloaded version of replace!
replace('a','b') example swap('b', 'a') example replace(by 'a')
To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.
If you want to replace multiple characters you can call the String. prototype. replace() with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping that you will use in that function.
To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.
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
String text = "Hambbburger";
text = text.replace('b', '\0');
The '\0'
represents NUL in ASCII code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With