Tuffy G
Tuffy G

Reputation: 1521

android replace multiple characters from a string

I know that this may be an amateur question but for some reason I can't remember how to do this. I have 2 strings.

String s ="[";
String q ="]";

if my text contains any of these i want to replace it with w which is:

String w = "";

I have tried the following:

output=String.valueOf(profile.get("text")).replace(s&&q, w);

from what i understand if of S([) and any of Q(]) are in text they will be replaced with w. my problem is getting the 2. if i only try and replace one then it will work. otherwise it wont.

any help would be appreciated

Upvotes: 4

Views: 17997

Answers (7)

Taimoor Mujahid
Taimoor Mujahid

Reputation: 1

For anyone looking for a solution in 2022, just do the following.

    String s = "[";
    String q = "]";
    String w = "";
    String text = Some[ Text ] here;
    
    text = text.replace(s, w );
    text = text.replace(q, w );
    String output = text;

Upvotes: 0

0xC0DED00D
0xC0DED00D

Reputation: 20348

You can nest them up too:

 output=String.valueOf(profile.get("text")).replace(s, w).replace(q, w);

Upvotes: 17

Ravi1187342
Ravi1187342

Reputation: 1277

check out this

String s ="[";
    String q ="]";
    String w = "";

    String output=w.replace("[", w);
    output=output.replace("]", w);

Upvotes: 0

bos
bos

Reputation: 6535

If you read on http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#replace%28char,%20char%29 you will see that it takes two char objects as an argument. The construction "s && q" and "s || q" are both illegal and gibberish. Think of it: what exactly would the logical operation ("foo" && "bar") return?

Do this:

output = String.valueOf(profile.get("text")).replace(q, w).replace(s, w);

This will yield what you want.

Upvotes: 1

Shankar Agarwal
Shankar Agarwal

Reputation: 34765

String s = "[";
String q = "]";
String w = "{";
String as = "sdada[sad]sdas";
String newstring = as.replace(s, w).replace(q,w);
Toast.makeText(_activity,newstring,Toast.LENGTH_LONG).show();

This is the working code for you...

Upvotes: 2

Deva
Deva

Reputation: 3949

try using replaceAll method from java.lang.String.

Upvotes: -1

hmjd
hmjd

Reputation: 121961

I think this is what you mean:

String s = "abc[def]";
String w = "hello";

System.out.println(s.replaceAll("\\[|\\]", w));

Outputs abchellodefhello.

String.replaceAll() accepts a regular expression as its first argument, which would provide the flexibility required.

Upvotes: 11

Related Questions