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!
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!
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("."),"");
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.
String text = "Hambbburger";
text = text.replace('b', '\0');
The '\0'
represents NUL in ASCII code.
replaceAll
in String doesnot work properly .It's Always recomend to use replace()
Ex:-
String s="abcdefabcdef";
s=s.replace("a","");
String str="aabbcc";
int n=str.length();
char ch[]=str.toCharArray();
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(ch[i]==ch[j])
{
ch[j]='*';
}
}
}
String temp=new String(ch);
for(int i=0;i<temp.length();i++)
{
if(temp.charAt(i)!='*')
System.out.print(temp.charAt(i));
}