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);

4 comments:

  1. It is really a great work and the way in which u r sharing the knowledge is excellent.
    Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article.
    Dot Net Training in chennai | Dot Net Training in velachery

    ReplyDelete


  2. Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information. dot net training and placement in chennai | dot net training in chennai

    ReplyDelete
  3. This blog is having the general information. Got a creative work and this is very different one.We have to develop our creativity mind.This blog helps for this. Thank you for this blog. This is very interesting and useful.
    Dot Net Training in Chennai

    ReplyDelete
  4. Nice and good article, thanks for sharing your valuable information about Dot Net. it is very useful for me. Thank you very much.
    Dot Net Training in chennai | Dot Net Training institute in velachery

    ReplyDelete