teepee
teepee

Reputation: 309

Find the first character in a string that is a letter

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.

Upvotes: 12

Views: 19039

Answers (3)

Michael Adamission
Michael Adamission

Reputation: 493

You should break this out to make sure there is a match, and to make sure there is a value at index 0... but it does work for this example case for demonstration purposes.

string test = "5604495Alpha";
var test2 = test.Remove(test.IndexOf(
    System.Text.RegularExpressions.Regex.Match(test, "[A-Za-z]").Index));
// test2 = "5604495"

Upvotes: 0

Simon Whitehead
Simon Whitehead

Reputation: 65079

A little method to do it:

int getIndexOfFirstLetter(string input) {
    var index = 0;
    foreach (var c in input)
        if (char.IsLetter(c))
            return index;
        else
            index++;

    return input.Length;
}

Usage:

var test = "5604495Alpha";

var result = test.Substring(0, getIndexOfFirstLetter(test));

// Returns 5604495

Upvotes: 1

Jim Mischel
Jim Mischel

Reputation: 133995

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

Upvotes: 29

Related Questions