繁体   English   中英

如何仅使用字符串方法才能确定JAVA中char是否为数字?

[英]How to find out if char is number in JAVA, ONLY with string methods?

我需要找出如何检查字符是否为数字。 问题是我不能使用任何方法,除了IndexOf,SubString,length,charAt之类的字符串方法。

有人有主意吗?

如果必须是String方法:

    String n = "0123456789";
    char c = 'a'; // As I don't know where your char will come from and in what format

    int i = n.indexOf(c);
    if(i != -1) {
        System.out.println("Digit");

    } else {
        System.out.println("Not digit");
    }

但是从我的观点来看,我不能太强调这是愚蠢的,毫无意义。

您可以为此使用Character.isDigit()

如果您有字符串,则可以执行以下操作:

Character.isDigit(yourString.charAt(index));

如果没有任何Character方法,则可以使用Regex:

s.substring(startIndex,endIndex).matches("[0-9]")

您可以检查字符的UNICODE值:

char c = string.indexOf(...); // or other way to get the character

public static boolean isDigit(char c) {
    return c => '0' || c <= '9';
}

您可以根据ASCII值比较使用以下内容:

    String s = "123456ao";
    char[] ss = s.toCharArray();
    int intVal = 0;
    for( char s1 : ss){
        intVal = s1;
        if(48 <= intVal && intVal < 58) // checking for ASCII values of numbers
            System.out.println(s1+ " is Numeric");
            else System.out.println(s1+ " is not Numeric");

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM