frankclaassens
frankclaassens

Reputation: 1930

Find index of first Char(Letter) in string

I have a mental block and can't seem to figure this out, sure its pretty easy 0_o

I have the following string: "5555S1"

String can contain any number of digits, followed by a Letter(A-Z), followed by numbers again. How do I get the index of the Letter(S), so that I can substring so get everything following the Letter

Ie: 5555S1 Should return S1

Cheers

Upvotes: 0

Views: 1861

Answers (4)

DarcyThomas
DarcyThomas

Reputation: 1288

This doesn't answer your question but it does solve your problem. (Although you can use it to work out the index)

Your problem is a good candidate for Regular Expressions (regex)

Here is one I prepared earlier:

    String code = "1234A0987";

    //timeout optional but needed for security (so bad guys dont overload your server)
    TimeSpan timeout = TimeSpan.FromMilliseconds(150);


   //Magic here:
   //Pattern == (Block of 1 or more numbers)(block of 1 or more not numbers)(Block of 1 or more numbers)                      
    String regexPattern = @"^(?<firstNum>\d+)(?<notNumber>\D+)(?<SecondNum>\d+)?";
    Regex r = new Regex(regexPattern, RegexOptions.None, timeout);

    Match m = r.Match(code);
    if (m.Success)//We got a match!
    {     
        Console.WriteLine ("SecondNumber: {0}",r.Match(code).Result("${SecondNum}"));
        Console.WriteLine("All data (formatted): {0}",r.Match(code).Result("${firstNum}-${notNumber}-${SecondNum}")); 

        Console.WriteLine("Offset length (not that you need it now): {0}", r.Match(code).Result("${firstNum}").Length); 

    }

Output:

SecondNumber: 0987 
All data (formatted): 1234-A-0987 
Offset length (not that you need it now): 4

Further info on this example here.

So there you go you can even work out what that index was.

Regex cheat sheet

Upvotes: 0

m3h2014
m3h2014

Reputation: 154

You could also check if the integer representation of the character is >= 65 && <=90.

Simple Python:

test = '5555Z187456764587368457638'

for i in range(0,len(test)):
    if test[i].isalpha():
            break

print test[i:]

Yields: Z187456764587368457638

Upvotes: 1

Dylan
Dylan

Reputation: 3

One way could be to loop through the string untill you find a letter.

while(! isAlpha(s[i]) i++; or something should work.

Upvotes: 0

Bryan
Bryan

Reputation: 5471

Given that you didn't say what language your using I'm going to pick the one I want to answer in - c#

String.Index see http://msdn.microsoft.com/en-us/library/system.string.indexof.aspx for more

for good measure here it is in java string.indexOf

Upvotes: 0

Related Questions