score:24

Accepted answer
new string("xq74mnt8244a".where(char.isdigit).toarray()) == "748244"

score:2

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

score:2

if you need only digits and you really want linq try this:

youstring.tochararray().where(x => char.isdigit(x)).toarray();

score:2

using linq:

public string filterstring(string input)
{
    return new string(input.where(char.isnumber).toarray());
}

score:2

something like this?


"xq74mnt8244a".tochararray().where(x => { var i = 0; return int32.tryparse(x.tostring(), out i); })

score:2

string s = "xq74mnt8244a";
var x = new string(s.where(c => (c >= '0' && c <= '9')).toarray());

score:6

string value = "htq7899hbvxzzxx";
console.writeline(new string(
     value.where(x => (x >= '0' && x <= '9'))
     .toarray()));

score:12

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


Related Query