Checking each character for a number

前端 未结 6 1397
别跟我提以往
别跟我提以往 2021-01-20 10:12

I am trying to loop through a string and check each character if one of the characters is a number. If it is a number, I want to return it as true. I have a string \"crash\"

6条回答
  •  悲&欢浪女
    2021-01-20 10:18

    Your code should work correctly, although I would probably use this instead:

    public boolean isNumber(String newString)
    {
        for (int i=0; i != newString.length(); i++)
        {
            if (!Character.isDigit(newString.charAt(i))) 
            {
                return false;
            }
        }
        return true;
    }
    
    // a regex equivalent
    public boolean isNumberRegex(String newString)
    {
        return newString.match("\\d+");
    }
    

    The method above checks if all characters are digits.

    If I misunderstood your question and you want to check if any of the characters is a digit:

    public boolean hasNumber(String newString)
    {
        for (int i=0; i != newString.length(); i++)
        {
            if (Character.isDigit(newString.charAt(i))) 
            {
                return true;
            }
        }
        return false;
    }
    
    // regex equivalent
    public boolean hasNumberRegex(String newString)
    {
        return newString.match(".*\\d.*");
    }
    

提交回复
热议问题