views:

339

answers:

10

Say for example I have the following string:

var testString = "Hello, world";

And I want to call the following methods:

var newString = testString.Replace("Hello", "").Replace("world", "");

Is there some code construct that simplifies this, so that I only have to specify the Replace method once, and can specify a bunch of parameters to pass to it in one go?

+1  A: 

Any construct that you come up with will probably be more complex than your original post. If you have a whole lot of different parameters to pass, you could construct a vector of those arguments and iterate over it performing the call. But then again, for your current example, the modified version would be longer and more complex to write. Twice is just too small a repetition rate.

David Rodríguez - dribeas
+3  A: 

Create a function to which you pass the String and a Dictionary(String, String). Iterate over each item in the Dictionary and InputString.Replace(DictionaryEntry.Key, DictionaryEntry.Value). Return the string with the replaced values.

But I'd just do .Replace.Replace if it's only 2 times...

Vincent Van Den Berghe
+1  A: 

You could create your own Replace extension method that takes a IEnumberable parameter. Then loop through the iterator and use the replace method.

Then you could call it like this .Replace(new string[] {"Matt", "Joanne", "Robert"}, "")

I think this should do it

public static string Replace(this string s, IEnumerable<string> strings, string replacementstring)
{
    foreach (var s1 in strings)
    {
        s = s.Replace(s1, replacementstring);
    }

    return s;
}
TT
why bother with the IEnumberable? and not just use the params key word?
Ray
It works, but it feels a bit iffy to me. I would use this only if I had to replace a lot of values in one go, in a lot of places. I can't really come up with a proper example where this would be applicable though.
Erik van Brakel
@Ray: seeing how all other parameters for this method are strings, it could be confusing when you use params string[] strings.
Erik van Brakel
+2  A: 

As noted in the other posts, there are many ways.

But generally sweet = efficient (= maintainable) = simple. It's probably best not to get try, unless there's some reason beyond which you are describing the question's context.

le dorfier
+3  A: 

Another option to make this more readable is to add new lines and proper indentation (which would be the better option to me):

var newString = testString.Replace("Hello", "")
                          .Replace("world", "")
                          .Replace("and", "")
                          .Replace("something", "")
                          .Replace("else","");
Erik van Brakel
A: 

I don't know if this is any sweeter, but you can do:

string inputString = "Hello, world";
string newString = new[] { "Hello", "world" }.Aggregate(inputString, (result, replace) => result.Replace(replace, ""));

This will start with the input string as the seed, and run thefunction with each of the replace strings.

A better example to understand the Aggregate function would perhaps be:

List<Payment> payments = ...;
double newDebt = payments.Aggregate(oldDebt, (debt, payment) => debt - payment.Amount);
Hallgrim
A: 

You could do it with a regular expression, something like:

var newString = Regex.Replace(testString, "Hello|world", "");

If you wanted to build the regex programmatically from a sequence it would be something like this:

var stringsToReplace = new[] { "Hello", "world" };
var regexParts = stringsToReplace.Select(Regex.Escape);
var regexText = string.Join("|", regexParts.ToArray());
Greg Beech
A: 

A lot of people are saying you should use IEnumerable and List and Arrays and such, and while that is perfectly "OK" I would rather use the params keyword in C# if I were you. IF I was to implement something like this though - which I probably wouldn't care to do for something such as easy as your double Replace method calls...

Thomas Hansen
+2  A: 

In some languages (e.g python) there is the concept of a reduce or fold function - which is a functional way of representing loops over all of the elements in a list.

Using reduce you can write something like this

return reduce(lambda a, x: a.Replace(x, ''), ['hello', 'world'], initial)

which is the same as

a = initial
for x in ['hello', 'world']:
    a = a.Replace(x, '')
return a

In python you can also pronounce this as

reduce(str.replace, ['hello', 'world'], initial).

Of course whether this is simpler is another question entirely - but a lot of people certainly enjoy writing code like this.

tatwright
A: 

There are several pitfalls to these patterns I am seeing - first of all, strings being immutable calling replace several times or in a loop can be bad, especially if your input string is large. If you are hell bent on calling replace then at least use the Replace method in the StringBuilder class.

keithwarren7