-4

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"

9
  • 3
    What would be the expected output? And why do you want to use LINQ when you don't have to? Commented Jul 14, 2017 at 6:47
  • 1
    do you want the digits in one array and the letters in a second array? Commented Jul 14, 2017 at 6:48
  • I want string in separate array and digits in separate link Commented Jul 14, 2017 at 6:49
  • 1
    Have you tried anything yourself? Sounds like regularexpression would be nice here. Commented Jul 14, 2017 at 6:49
  • 1
    Why does it have to be LINQ? The Q stands for "Query Language", not manipulation Commented Jul 14, 2017 at 6:49

3 Answers 3

3

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Very elegant solution
@DeadlyEmbrace thank you, but it strongly depends on what op expects as result. It might be useless for him, if he needs the single elements still separated as in the original string like "abcd" and "pqr"
1

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.

1 Comment

Thank you guys I resolve my problem .
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.