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
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
new string("XQ74MNT8244A".Where(char.IsDigit).ToArray()) == "748244"
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]+
.
string value = "HTQ7899HBVxzzxx";
Console.WriteLine(new string(
value.Where(x => (x >= '0' && x <= '9'))
.ToArray()));
If you need only digits and you really want Linq try this:
youstring.ToCharArray().Where(x => char.IsDigit(x)).ToArray();
Using LINQ:
public string FilterString(string input)
{
return new string(input.Where(char.IsNumber).ToArray());
}
Something like this?
"XQ74MNT8244A".ToCharArray().Where(x => { var i = 0; return Int32.TryParse(x.ToString(), out i); })
string s = "XQ74MNT8244A";
var x = new string(s.Where(c => (c >= '0' && c <= '9')).ToArray());
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();