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?
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.
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.
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.
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.
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With