Bart
Bart

Reputation: 4920

how to replace multiple chars from a string?

what is the equivalent of below:

contact.name.Replace("(", "").Replace(")", "").Replace("-", "").Replace(" ", "");

Thanks

Upvotes: 0

Views: 98

Answers (3)

Vlad Bezden
Vlad Bezden

Reputation: 89499

Using LINQ:

var s = "abcd 238(23)2342-23";
var exclusion = "()- ";

var result = new string(s.ToCharArray().Where (x => !exclusion.Contains(x)).ToArray());

or

var s = "abcd 238(23)2342-23";

var result = new string(s.ToCharArray().Where (x => !"()- ".Contains(x)).ToArray());

Upvotes: 1

Brad Bruce
Brad Bruce

Reputation: 7807

StringBuilder will be more effecient if you're doing more than a few replacements.

Upvotes: 0

Dan F
Dan F

Reputation: 12052

Regular Expression Replace should do the trick

contact.name = Regex.Replace(contact.name, @"[\(\)\- ]", String.Empty);

Upvotes: 2

Related Questions