How to remove characters from a string using LINQ

2020-04-02 08:03发布

问题:

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

回答1:

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


回答2:

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]+.



回答3:

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


回答4:

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

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


回答5:

Using LINQ:

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


回答6:

Something like this?


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


回答7:

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


回答8:

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