Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the first character in a string that is a letter

Tags:

string

c#

char

I am trying to figure out how to look through a string, find the first character that is a letter and then delete from that index point and on.

For example,

string test = "5604495Alpha";

I need to go through this string, find "A" and delete from that point on.

like image 405
teepee Avatar asked Jun 04 '14 04:06

teepee


1 Answers

There are several ways to do this. Two examples:

string s = "12345Alpha";
s = new string(s.TakeWhile(Char.IsDigit).ToArray());

Or, more correctly, as Baldrick pointed out in his comment, find the first letter:

s = new string(s.TakeWhile(c => !Char.IsLetter(c)).ToArray());

Or, you can write a loop:

int pos = 0;
while (!Char.IsLetter(s[pos]))
{
    ++pos;
}
s = s.Substring(0, pos);
like image 98
Jim Mischel Avatar answered Nov 15 '22 17:11

Jim Mischel