如何将字符串对象转换为布尔对象?
当前回答
在使用Boolean.valueOf(string)或Boolean.parseBoolean(string)时必须小心。这样做的原因是,如果String不等于“true”,方法总是返回false(这种情况会被忽略)。
例如:
Boolean.valueOf("YES") -> false
由于这种行为,我建议添加一些机制来确保应该转换为布尔值的字符串遵循指定的格式。
例如:
if (string.equalsIgnoreCase("true") || string.equalsIgnoreCase("false")) {
Boolean.valueOf(string)
// do something
} else {
// throw some exception
}
其他回答
public static boolean stringToBool(String s) {
s = s.toLowerCase();
Set<String> trueSet = new HashSet<String>(Arrays.asList("1", "true", "yes"));
Set<String> falseSet = new HashSet<String>(Arrays.asList("0", "false", "no"));
if (trueSet.contains(s))
return true;
if (falseSet.contains(s))
return false;
throw new IllegalArgumentException(s + " is not a boolean.");
}
我把字符串转换成布尔值的方法。
boolean status=false;
if (variable.equalsIgnoreCase("true")) {
status=true;
}
仅当字符串为'true'(不区分大小写)时才支持。稍后您可以使用状态变量。
访问http://msdn.microsoft.com/en-us/library/system.boolean.parse.aspx
这会让你知道该怎么做。
这是我从Java文档中得到的:
方法的细节 parseBoolean parseBoolean(String s) 将字符串参数解析为布尔值。如果字符串参数不为空,返回的布尔值表示true,并且忽略大小写,等于字符串"true"。 参数: s -包含要解析的布尔表示的字符串 返回:由字符串参数表示的布尔值 自: 1.5
为什么不用正则表达式呢?
public static boolean toBoolean( String target )
{
if( target == null ) return false;
return target.matches( "(?i:^(1|true|yes|oui|vrai|y)$)" );
}
Boolean b = Boolean.valueOf(string);
如果字符串不是空值并且等于true(忽略大小写),则b的值为true。
推荐文章
- Intellij IDEA Java类在保存时不能自动编译
- 何时使用Mockito.verify()?
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址
- 如何在Java中打印二叉树图?
- String.format()在Java中格式化双重格式
- com.jcraft.jsch.JSchException: UnknownHostKey
- Java中的操作符重载
- 如何加速gwt编译器?
- 如何删除表中特定列的第一个字符?
- 在Hibernate中重新连接分离对象的正确方法是什么?