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
Read More..
 
[32134 clicks]
Published under:
Microsoft .NET Tips · · · ·