Getting Started with ASP.NET MVC - Part 6: ASP.NET MVC and Entity Framework
First Time? You can support us by signing up. It takes only 5 seconds. Click here to sign up. If you already have an account, click here to login.


Upload Image Close it
Select File

Share a .NET tip or learn from what others have shraed.

Different ways of Removing spaces,dots(.),hyphens(-),braces '(' and ')' from string

Sep 16 2011 12:02AM by Niladri Biswas   

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..  [5005 clicks]


Niladri Biswas
5 · 29% · 6617
16
 
1
 
14
 
0
Incorrect
 
0
Interesting
 
 
0
Move



Submit

1  Comments  

  • nice post

    commented on Sep 17 2011 2:27AM  .  Report Abuse This post is not formatted correctly
    Srikanth Reddy
    731 · 0% · 24

Your Comment


Sign Up or Login to post a comment.

"Different ways of Removing spaces,dots(.),hyphens(-),braces '(' and ')' from string" rated 5 out of 5 by 16 readers
Different ways of Removing spaces,dots(.),hyphens(-),braces '(' and ')' from string , 5.0 out of 5 based on 16 ratings
    Copyright © Beyondrelational.com Contact us      Privacy Policy      Terms of use      Report Abuse      Advertising