views:

59

answers:

2

Hi.

How do I remove all matching substrings in a string? For example if I have 20 40 30 30 30 30, then I just 20 40 30 (and not the other 30s). Do I use a regex? If so, how?

+8  A: 

If these "substrings" are all separated by whitespace, you could just split it, and take the distinct items and recreate the string.

var str = "20 40 30 30 30 30";
var distinctstr = String.Join(" ", str.Split().Distinct());
Jeff M
+1. Much easier than how I've been doing it. am falling so far behind... I haven't done a lot with Linq, even though it's been around for a while, so I never even HEARD of the Enumerable.Distinct() method. Thank you!
David Stratton
Yes, they are separated by whitespaces. Also, I didn't know about the Distinct() method, thanks for the info!
david
@David Stratton: Play with LINQ as often as you can. And it doesn't have to be writing just queries. Things like this are just as good. It helps making working with collections _so_ much easier. I'd say, use it everywhere you can at first until you are comfortable thinking code in terms of using LINQ. Then as you understand the limits of its abilities, you'll know what it is and isn't useful for.
Jeff M
A: 

I think the right answer given your question is to use the replace function:

string newString = oldString.Replace("30", "");

or

string newString = orldString.Replace(" 30", "");

to get rid of the blanks..,

Edit just reread... My mistake. sorry. Didn't realise you wanted to keep a single '30'.

ach