954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

A way to remove an unwanted char from a string

0
By Marivoet Daniel on Jan 21st, 2012 7:22 pm

Short snippet on how you could remove all occurrences of a char from a string using LINQ.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQTesting
{
    class Program
    {
        static void Main(string[] args)
        {
            const char UnwantedChar = '.';

            string Date = "12.11.1976";
            var DateWithout = new char[8];

            Console.WriteLine("Original date = {0}",Date);
            
            // Get some help from LINQ
            IEnumerable<Char> WithoutTheChar = Date.Where(ch => !ch.Equals(UnwantedChar));

            int CharCount = 0;
            foreach (char ch in WithoutTheChar) //enumerate
            {
                DateWithout[CharCount] = ch;
                CharCount++;
            }

            string NewDate = new String(DateWithout);
            Console.WriteLine("Date cleaned up = {0}", NewDate);
           
            Console.ReadKey();
        }
    }
}

Think this is an improved version:

namespace LINQTesting
{
    class Program
    {
        static void Main(string[] args)
        {
            const char UnwantedChar = '.';

            string Date = "12.11.1976";

            Console.WriteLine("Original date = {0}",Date);
            
            // Get some help from LINQ
            char[] WithoutTheChar = Date.Where(ch => !ch.Equals(UnwantedChar)).ToArray();
            // convert array of char to string
            string NewDate = new String(WithoutTheChar);
           
            Console.WriteLine("Date cleaned up = {0}", NewDate);
           
            Console.ReadKey();
        }
    }
}
ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
 

Why not use String.Replace()?

string NewDate = Date.Replace(".", string.Empty);
deceptikon
Indubitably
Administrator
633 posts since Jan 2012
Reputation Points: 119
Solved Threads: 105
 

@deceptikon: yes you are right!
But I titled this snippet A way, not THE way
I think your suggestion is perhaps the preferred way.

ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: