Search code examples
javaletter

Find first letter in a string


My program uses an ID system that requires 1-3 digits before a letter then 1-3 digits following the character. For example: 12a123 or 1b83, etc.

What I'm trying to find out is how to find the first occurrence of a letter in the string so I can store the letter as it’s used for an operation between the digits later.

Thanks :)


Solution

  • Just loop through the characters and grab the first one in the range upper/lowercase A-Z.

    public char getCharacter(final String code)
    {
        for (char character : code.toCharArray())
        {
            if (   (character >= 'a' && character <= 'z')
                || (character >= 'A' && character <= 'Z'))
            {
                return character;
            }
        }
        throw new RuntimeException("No character in ID: " + code);
    }