aman shrivastava
aman shrivastava

Reputation: 23

String replace() in java

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

Answers (5)

aman shrivastava
aman shrivastava

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

Ahmed ElGreetly
Ahmed ElGreetly

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

Ishara Dayarathna
Ishara Dayarathna

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

Charis Moutafidis
Charis Moutafidis

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

Turan
Turan

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

Related Questions