gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 08:39:59 27 4
gpt4 key购买 nike

我有一个 String,有时值会改变:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com