I have one string having numbers and alphabets want to split alphabets and digits in separate array using LINQ query in C# .my string is as
"abcd 00001 pqr 003 xyz abc 0009"
I have one string having numbers and alphabets want to split alphabets and digits in separate array using LINQ query in C# .my string is as
"abcd 00001 pqr 003 xyz abc 0009"
you could transform the string to an char array and then use the Where
clause to extract the necessary information:
string g = "abcd 00001 pqr 003 xyz abc 0009";
char[] numbers = g.ToCharArray().Where(x => char.IsNumber(x)).ToArray();
char[] letters = g.ToCharArray().Where(x=> char.IsLetter(x)).ToArray();
You can do it in this way:
string a ="abcd 00001 pqr 003 xyz abc 0009";
var digits = a.Split().Where(x=> {double number; return double.TryParse(x,out number);});
var letters = a.Split().Where(x=> {double number; return !double.TryParse(x,out number);});
foreach(var a1 in digits)
{
Console.WriteLine(a1);
}
foreach(var a1 in letters)
{
Console.WriteLine(a1);
}
The idea is to try to Parse the character and if it is parsed successful then it's a number.
You can use GroupBy
where the Key is a boolean
that specifies if the entry is a number(Can be converted to a double
) or text:
string input = "abcd 00001 pqr 003 xyz abc 0009";
double dummy;
var result = input.Split().GroupBy(i => double.TryParse(i, out dummy)).ToList();
var textArray = result.Where(i => !i.Key).SelectMany(i=> i).ToArray();
var numberArray = result.Where(i => i.Key).SelectMany(i => i.ToList()).ToArray();