Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

replace

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!

like image 527
Oh Chin Boon Avatar asked Aug 10 '11 15:08

Oh Chin Boon


People also ask

How can you replace all occurrences of the letter A with the letter B?

replace('a','b') example swap('b', 'a') example replace(by 'a')

How do you replace every instance of a character in a string?

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.

How do you replace multiple characters?

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.

How do you replace a character in a string without replace?

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.


3 Answers

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("."),"");
like image 80
Pablo Fernandez Avatar answered Nov 16 '22 02:11

Pablo Fernandez


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

like image 44
MByD Avatar answered Nov 16 '22 01:11

MByD


String text = "Hambbburger";
text = text.replace('b', '\0');

The '\0' represents NUL in ASCII code.

like image 35
Gavin Avatar answered Nov 16 '22 01:11

Gavin