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"
Where(char.IsDigit) work in this case? I would think that you have to write Where(c => char.IsDigit(c)) here? Does the compiler do some magic in this case? An explanation would be appreciated here.Char.IsDigit is a function that takes a char and return a bool - exactly what Where expects. You don't have to wrap it in an anonymous function. (oh, and the compiler does a lot of magic anyway, like anonymous functions)Where method; lambda syntax is only one way to obtain a delegate. If your lambda makes a direct call to some method, and the method's parameter types and return type match those of the lambda, you can provide the method name directly.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]+.
IEnumerable<char>, so it fits nicely, and probably optimized for that.If you need only digits and you really want Linq try this:
youstring.ToCharArray().Where(x => char.IsDigit(x)).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();
regex- see @Tim Robinson's answer.RegExbased solution.