我有一个字符串
,有时值会改变:
String str1 = "+25"; // only have "+" sign and number
String str2 = "+Name"; // only have "+" sign and text
我如何区分这些String
,因为我想做这样的事情:
if (isString1Type) { // both strings also have "+" sign
// do something
}
String
对于这种情况有任何函数吗?
谁能给我建议吗?
最佳答案
是的,你可以这样做:
String str = "+Name";
boolean hasPlusSign = str.contains("+");
boolean isNumber = tryParseInt(str.replace("+", ""));
if(hasPlusSign && isNumber){ //if the string is +25 for example here will be true, else it will go to the else statement
//do something
} else {
//something else
}
boolean tryParseInt(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
关于android - 检查字符串是否仅包含 "+"符号和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33689467/