Thomas Anderson
Thomas Anderson

Reputation: 2067

How to remove characters from a string using LINQ

I'm having a String like

XQ74MNT8244A

i nee to remove all the char from the string.

so the output will be like

748244

How to do this? Please help me to do this

Upvotes: 10

Views: 10440

Answers (8)

Kobi
Kobi

Reputation: 138147

Two options. Using Linq on .Net 4 (on 3.5 it is similar - it doesn't have that many overloads of all methods):

string s1 = String.Concat(str.Where(Char.IsDigit));

Or, using a regular expression:

string s2 = Regex.Replace(str, @"\D+", "");

I should add that IsDigit and \D are Unicode-aware, so it accepts quite a few digits besides 0-9, for example "542abc٣٤".
You can easily adapt them to a check between 0 and 9, or to [^0-9]+.

Upvotes: 12

Flipster
Flipster

Reputation: 4401

How about an extension method (and overload) that does this for you:

    public static string NumbersOnly(this string Instring)
    {
        return Instring.NumbersOnly("");
    }

    public static string NumbersOnly(this string Instring, string AlsoAllowed)
    {
        char[] aChar = Instring.ToCharArray();
        int intCount = 0;
        string strTemp = "";

        for (intCount = 0; intCount <= Instring.Length - 1; intCount++)
        {
            if (char.IsNumber(aChar[intCount]) || AlsoAllowed.IndexOf(aChar[intCount]) > -1)
            {
                strTemp = strTemp + aChar[intCount];
            }
        }

        return strTemp;
    }

The overload is so you can retain "-", "$" or "." as well, if you wish (instead of strictly numbers).

Usage:

string numsOnly = "XQ74MNT8244A".NumbersOnly();

Upvotes: 2

Vlad
Vlad

Reputation: 35594

string s = "XQ74MNT8244A";
var x = new string(s.Where(c => (c >= '0' && c <= '9')).ToArray());

Upvotes: 2

tucaz
tucaz

Reputation: 6684

Something like this?


"XQ74MNT8244A".ToCharArray().Where(x => { var i = 0; return Int32.TryParse(x.ToString(), out i); })

Upvotes: 2

Arcturus
Arcturus

Reputation: 27065

Using LINQ:

public string FilterString(string input)
{
    return new string(input.Where(char.IsNumber).ToArray());
}

Upvotes: 2

UserControl
UserControl

Reputation: 15179

If you need only digits and you really want Linq try this:

youstring.ToCharArray().Where(x => char.IsDigit(x)).ToArray();

Upvotes: 2

Aliostad
Aliostad

Reputation: 81700

string value = "HTQ7899HBVxzzxx";
Console.WriteLine(new string(
     value.Where(x => (x >= '0' && x <= '9'))
     .ToArray()));

Upvotes: 6

Tim Robinson
Tim Robinson

Reputation: 54774

new string("XQ74MNT8244A".Where(char.IsDigit).ToArray()) == "748244"

Upvotes: 24

Related Questions