user3589316
user3589316

Reputation: 21

Multiple replace in one statement

test = test.replace("COOL", "");
        test = test.replace(" ", "");
        test = test.replace("GRUPPE=", "");
        test = test.replace("\n", "");
        test = test.replace("\r", "");

This is only an example. There are 20 more Strings which I want to replace.

And now I want to get this in only one statement. Is there any possibility of doing this? Or is the code the "best" for doing this?

I develop for JAVA.

Upvotes: 0

Views: 122

Answers (4)

Suren Raju
Suren Raju

Reputation: 3060

Use Apache StringUtils replaceEach method

StringUtils.replaceEach(text, new String[]{"COOL", "GRUPPE"}, new String[]{"", ""}) ;

Apache StringUtils

Upvotes: 1

Neel
Neel

Reputation: 11721

Try below code.

     var array = new string[] { "COOL", "gruppe", "\n" };
     string test = "COOL gruppe test";
    foreach(var result in array)
    {
          test = test.Replace(result, "");
    }

Upvotes: 0

anirudh
anirudh

Reputation: 4176

If you are going to replace all instances of those words, you can do it like this

test.replaceAll("COOL|\\s+|GRUPPE", "");

\\s+ is taken by regex as \s+ which includes white spaces and new line characters.

Upvotes: 2

user1796756
user1796756

Reputation:

you can use regular expressions for that.

so you will need something like:

rest.replaceAll("(COOL|\s|GRUPPE=|\n|\r)", "")

in regex you join different variants with | symbol which means OR.

Upvotes: 1

Related Questions