Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to multiple String.Replaces [duplicate]

Tags:

string

c#

replace

My code uses String.Replace several times in a row:

mystring = mystring.Replace("somestring", variable1); mystring = mystring.Replace("somestring2", variable2); mystring = mystring.Replace("somestring3", variable1); 

I suspect there's a better and faster way to do it. What would you suggest?

like image 705
Petter Brodin Avatar asked Aug 17 '12 14:08

Petter Brodin


People also ask

How do you replace multiple values in a string?

Show activity on this post. var str = "I have a cat, a dog, and a goat."; str = str. replace(/goat/i, "cat"); // now str = "I have a cat, a dog, and a cat." str = str. replace(/dog/i, "goat"); // now str = "I have a cat, a goat, and a cat." str = str.

How do I replace multiple characters in a string?

If you want to replace multiple characters you can call the String. prototype. replace() with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping which you will use in that function.

How do you replace multiple occurrences of a string in Java?

You can replace all occurrence of a single character, or a substring of a given String in Java using the replaceAll() method of java. lang. String class. This method also allows you to specify the target substring using the regular expression, which means you can use this to remove all white space from String.

How do you replace multiple values in Python?

To replace multiple values in a DataFrame we can apply the method DataFrame. replace(). In Pandas DataFrame replace method is used to replace values within a dataframe object.


2 Answers

For an 'easy' alternative just use a StringBuilder....

StringBuilder sb = new StringBuilder("11223344");  string myString =     sb       .Replace("1", string.Empty)       .Replace("2", string.Empty)       .Replace("3", string.Empty)       .ToString(); 
like image 117
Rostov Avatar answered Oct 18 '22 16:10

Rostov


Are we going for ways to make this harder to understand what is going on?

If so regex is your friend

var replacements = new Dictionary<string,string>() {    {"somestring",someVariable1},    {"anotherstring",someVariable2} };  var regex = new Regex(String.Join("|",replacements.Keys.Select(k => Regex.Escape(k)))); var replaced = regex.Replace(input,m => replacements[m.Value]); 

Live: http://rextester.com/SXXB8348

like image 43
Jamiec Avatar answered Oct 18 '22 14:10

Jamiec