Checking each character for a number

前端 未结 6 1388
别跟我提以往
别跟我提以往 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:24

    Well you can use Integer.parseInt("string") and catch the exception.

    try {
         int num = Integer.parseInt("string");
         return true;
    } catch (NumberFormatException nfe) {
         return false;
    }
    

    Or another way with regEx:

    if ("string".replaceAll("\\d+","").length() > 0) { 
        //false 
    } else { 
        //true
    }
    

提交回复
热议问题