Reputation: 23
We have a
String s="my name is bob";
System.out.print(s.replace("a","p")); // so here a replace to p
but I want a variable in the place of a
example
char o='a';
system.out.print(s.replace(o,"p"));
But here it is giving an error so how can be put a variable inside a replace method is there any way to do it?
Upvotes: 0
Views: 745
Reputation: 23
Guys I found it by my self just check the answer
public class HelloWorld
{
public static void main(String []args){
String s="my name is aman shrivastava";
String p = "a";
System.out.println(s.replace(p,"s"));
//or
char e='a';
String ps=Character.toString(e);
System.out.println(s.replace(ps,""));
System.out.println(s);
}
}
Upvotes: 0
Reputation: 31
The two variables you give to String.replace
have to be the same value (""
). This means what's in is a string so you have to change "p"
to 'p'
or change char o = 'a'
to String o = "a"
.
Upvotes: 2
Reputation: 3601
There is no suitable method found for replace(char,String)
Try this:
String s="my name is bob";
String o="a";
System.out.print(s.replace(o,"p"));
Upvotes: 0
Reputation: 363
Change char o to String o
Replace is expecting string parameters Also try using replaceAll() if you what to replace all these characters, not just the first one.
Upvotes: 0
Reputation: 302
String replace takes two chars as its input and replaces the old with the new. For your example you'd need to make the p a char.
String s="my name is bob";
System.out.print(s.replace('a','p'));
//Result - my npme is bob
Upvotes: 1