[英]How to find out if char is number in JAVA, ONLY with string methods?
I need to find out how can I check if a char is a number. 我需要找出如何检查字符是否为数字。 The problem is that I can't use any methods except string methods like IndexOf, SubString, length, charAt. 问题是我不能使用任何方法,除了IndexOf,SubString,length,charAt之类的字符串方法。
Does anyone have an idea? 有人有主意吗?
If it has to be String methods: 如果必须是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");
}
But I can't stress enough that this is, well, idiotic and pointless from my point of view. 但是从我的观点来看,我不能太强调这是愚蠢的,毫无意义。
You can use Character.isDigit()
for this. 您可以为此使用Character.isDigit()
。
If you have a string, you can do this : 如果您有字符串,则可以执行以下操作:
Character.isDigit(yourString.charAt(index));
And withtout any Character method you can use Regex : 如果没有任何Character方法,则可以使用Regex:
s.substring(startIndex,endIndex).matches("[0-9]")
You can check the character for its UNICODE value: 您可以检查字符的UNICODE值:
char c = string.indexOf(...); // or other way to get the character
public static boolean isDigit(char c) {
return c => '0' || c <= '9';
}
You can use the below based on the ASCII values comparison:- 您可以根据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.