Remove spaces,dots(.),hyphens(-),braces '(' and ')' from string

Niladri.biswas
Posted by Niladri.biswas under C# category on | Points: 40 | Views : 9839
Recently a colleague of mine asked me to give him a code for replacing spaces,dots(.),hyphens(-),braces '(' and ')'.

Here is my solution

string str= "This is a string having - and - - - - It also has dot (.) Many dots(.....)";

Approach 1: Using lambda and extension methods

var way1 = str
.ToCharArray()
.Where(i =>
i != ' ' &&
i != '-' &&
i != '.' &&
i != '(' &&
i != ')'
)
.Aggregate(" ", (a, b) => a + b);

Approach 2: Using string concat function and lambda and extension method

 var way2= string.Concat(str.Where(i => !new[] { '.', ' ', '-', '(' ,')'}.Contains(i)));


Approach 3: Using regular expression

 var way3 = Regex.Replace(str, "[ ().-]+", "");


OUTPUT

ThisisastringhavingandItalsohasdotManydots

Thanks

Comments or Responses

Posted by: SheoNarayan on: 9/16/2011 Level:HonoraryPlatinum | Status: [Administrator] | Points: 10
Excellent Niladari,

Is there a way to allow only Alphanumeric characters (A-Z, 0-9) and - in the string?
And
Is there any way to remove all other characters except A-Z, 0-9 and replace " " to "-" from a string?

This would be helpful.

Thanks
Regards
Posted by: Niladri.biswas on: 9/18/2011 Level:Platinum | Status: [Member] | Points: 10
I think both the questions are interrelated.
However here is what I have come out with

string str = "Hello this is a string...Phno Numbner: 9665110000;;;;Are u happy?[]"; 

var finalResult = Regex.Replace(Regex.Replace(str, "\\s+", "-"), "[^a-zA-Z0-9-]+", "");


Explanation
var res1 = Regex.Replace(str, "\\s+", "-")

Replaces " " to "-" . This becomes the input for the next one
var res2 = Regex.Replace(res1, "[^a-zA-Z0-9-]+", "");


Output
Hello-this-is-a-stringPhno-Numbner-9665110000Are-u-happy
Posted by: SheoNarayan on: 9/19/2011 Level:HonoraryPlatinum | Status: [Administrator] | Points: 10
Thanks Niladari !

Login to post response