android - 检查字符串是否仅包含 "+"符号和数字

标签 android

我有一个字符串,有时值会改变:

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/

相关文章:

java - Android html POST 不工作,没有给出错误

android - 字符串到字符序列

android - 使用 OnTouchEvent 移动 View

java - Android 上 GeoPoint 的空指针异常

php - 安全证书

android - 如何更改android中下划线的颜色

android - 为 Android 库项目中的 AAR Artifact 指定部署的文件名

android - 如何在搜索栏中设置双值

android - 为整个 Activity 设置字体设置

Android OpenCV 与 JNI 性能不佳