Remove dots(.), hyphens(-), spaces,braces’(‘ and ‘)’ from string in C#

If you want to remove dots(.), hyphens(-), spaces, braces ‘(‘ and ‘)’ from a string in C# then you can use any solution given below.

string str = "A sample string having many . and ......It also has a hyphen (-) and too Many hyphens(------) Enjoy!!";

// Solution1: Use of String concat Function and Lambda Extension Method
var solution1 = string.Concat(str.Where(i => !new[] { '.', ' ', '-', '(', ')' }.Contains(i)));

Response.Write(solution1);


// Solution2: Use of Regular Expression. (Make sure you add using System.Text.RegularExpressions; on top of your page before using below solution2)
var solution2 = Regex.Replace(str, "[ ().-]+", "");

Response.Write(solution2);
           
           
// Solution3 : Use of Lambda and Extension Methods
var solution3 = str.ToCharArray().Where(i => i != ' ' && i != '-' && i != '.' && i != '(' && i != ')' ).Aggregate(" ", (a, b) => a + b);

Response.Write(solution3);

1 comment: