How to find the index of the first digit in a string with Java

1 Answer

0 votes
public class MyClass
{
    public static int indexOfAny(String string, char[] anyOf) {
        int lowestIndex = -1;
         
        for (char ch : anyOf) {
            int index = string.indexOf(ch);
            if (index > -1)  {
                if (lowestIndex == -1 || index < lowestIndex) {
                    lowestIndex = index;
                    if (index == 0) {
                        break;
                    }
                }
            }
        }
 
        return lowestIndex;
    }
     
    public static void main(String[] args)
    {
        String str = "java programming 98";
         
        int i = indexOfAny(str, new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'});
         
        System.out.print(i);
    }
}




/*
run:
 
17
 
*/

 



answered Aug 31, 2023 by avibootz
...