Question

I have a string which its first part is a string and last one is a number, like this:

ahde7394

so what I would like to obtain is:

ahde

7394

I have thought to first extract the string and then from the last position of the character obtain the number until the end of the string so I think using indexers can be done somehow:

var stringQuery = NameComp.Select((str,index) => new {myStr=str, position=index})
                                               .Where(c => !Char.IsDigit(c.myStr)).Select((ch,pos) => new { newStr=ch, pos=pos} );

then I could do:

1) To obtain the string: stringQuery.newStr

2) To obtain the number: stringQuery.Skip(stringQuery.pos).Select(d => d);

but it is not working, after obtaining stringQuery I cannot access to its items as it is an anonymous type....

Any ideas?

Solution using LINQ, guessing that str="ahde7394":

string letters = new string(str.TakeWhile(c => Char.IsLetter(c)).ToArray());

and for number:

string number = new string(str.Skip(letters.Length).TakeWhile(c => Char.IsDigit(c)).ToArray());

or better guessing last part is a number:

   string number = str.Substring(name.Length);
Was it helpful?

Solution

I agree with dtb that LINQ is probably not the right solution.

Regex is another option, assuming that your string can be much more variable than you have provided.

var str = "ahde7394";

var regex = Regex.Match(str, @"([a-zA-Z]+)(\d+)");

var letters = regex.Groups[1].Value; // ahde
var numbers = regex.Groups[2].Value; // 7394

OTHER TIPS

LINQ might not be the best solution here. Have a look at the String.IndexOfAny Method:

char[] digits = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

string input = "ahde7394";

int index = input.IndexOfAny(digits);

string head = input.Substring(0, index);  // "ahde"
string tail = input.Substring(index);     // "7394"

You can use String.IndexOf and String.Substring like;

string s = "ahde7394";
int index = 0;
foreach (var i in s)
{
     if(Char.IsDigit(i))
     {
        index = s.IndexOf(i);
        break;
     }
}

Console.WriteLine(s.Substring(0, index));
Console.WriteLine(s.Substring(index));

Output will be;

ahde
7394

Here a DEMO.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top