Rag*_*nar 38 java string boolean
我对此做了一点搜索,但找不到任何有用的东西.
关键是如果String值为"true"或"false",则返回值应为true.在其他每一个值中都应该是假的.
我试过这些:
String value = "false";
System.out.println("test1: " + Boolean.parseBoolean(value));
System.out.println("test2: " + Boolean.valueOf(value));
System.out.println("test3: " + Boolean.getBoolean(value));
Run Code Online (Sandbox Code Playgroud)
所有函数返回false :(
mfx*_*mfx 53
没有方法来测试String是否编码布尔值; 对于所有实际效果,任何非"true"-String都是"false".
Bom*_*mbe 37
return "true".equals(value) || "false".equals(value);
Run Code Online (Sandbox Code Playgroud)
Bil*_*Man 17
Apache commons-lang3的BooleanUtils带有toBooleanObject方法:
BooleanUtils.toBooleanObject(String str)
// where:
BooleanUtils.toBooleanObject(null) = null
BooleanUtils.toBooleanObject("true") = Boolean.TRUE
BooleanUtils.toBooleanObject("false") = Boolean.FALSE
BooleanUtils.toBooleanObject("on") = Boolean.TRUE
BooleanUtils.toBooleanObject("ON") = Boolean.TRUE
BooleanUtils.toBooleanObject("off") = Boolean.FALSE
BooleanUtils.toBooleanObject("oFf") = Boolean.FALSE
BooleanUtils.toBooleanObject("blue") = null
Run Code Online (Sandbox Code Playgroud)
小智 5
if ("true".equals(value) || "false".equals(value)) {
// do something
} else {
// do something else
}
Run Code Online (Sandbox Code Playgroud)
小智 5
也可以通过正则表达式来完成:
Pattern queryLangPattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
Matcher matcher = queryLangPattern.matcher(booleanParam);
return matcher.matches();
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用以下方法来检查值是否为布尔值:
boolean isBoolean(String value) {
return value != null && Arrays.stream(new String[]{"true", "false", "1", "0"})
.anyMatch(b -> b.equalsIgnoreCase(value));
}
Run Code Online (Sandbox Code Playgroud)
使用它的例子:
System.out.println(isBoolean(null)); //false
System.out.println(isBoolean("")); //false
System.out.println(isBoolean("true")); //true
System.out.println(isBoolean("fALsE")); //true
System.out.println(isBoolean("asdf")); //false
System.out.println(isBoolean("01truefalse")); //false
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
99045 次 |
| 最近记录: |