0

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?

5
  • 3
    String o="a"; Commented Apr 22, 2018 at 11:48
  • Make o a String Commented Apr 22, 2018 at 11:48
  • 2
    or system.out.print(s.replace(o,'p')); if you want to replace a single char with a single char. Commented Apr 22, 2018 at 11:49
  • 1
    Because there is no such method. The .replace() has two signatures, one of which is replace(char,char) and second is replace(CharSequence, CharSequence). Commented Apr 22, 2018 at 11:51
  • Please look carefully at your code. In your first example you use a String for "a" but in your second example you define it as char. Commented Apr 22, 2018 at 11:55

5 Answers 5

2

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".

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

I already mention it in my question then also thank you for your time I got the answer
0

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.

Comments

0

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"));

1 Comment

yes thankyou for your solution the first argument . should be a string type only
0

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);                      
     }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.