david
david

Reputation: 367

C# Replacing matching substrings in a string

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?

Upvotes: 0

Views: 5828

Answers (2)

Andrew Hanlon
Andrew Hanlon

Reputation: 7421

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'.

Upvotes: 2

Jeff Mercado
Jeff Mercado

Reputation: 134841

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());

Upvotes: 9

Related Questions