如何将字符串对象转换为布尔对象?
当前回答
在使用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
}
其他回答
除了KLE这个优秀的答案,我们还可以做一些更灵活的事情:
boolean b = string.equalsIgnoreCase("true") || string.equalsIgnoreCase("t") ||
string.equalsIgnoreCase("yes") || string.equalsIgnoreCase("y") ||
string.equalsIgnoreCase("sure") || string.equalsIgnoreCase("aye") ||
string.equalsIgnoreCase("oui") || string.equalsIgnoreCase("vrai");
(受到zlajo的回答启发……: -))
在2018年1月,最好的方法是使用apache的BooleanUtils.toBoolean。
这将把任何布尔值如字符串转换为布尔值,例如Y, yes, true, N, no, false等。
非常方便!
如果你的目标只是将这个字符串变量与“false”或“true”字符串进行比较,而不硬编码这两个值,就像我的情况一样,并且你不想使用Boolean.valueOf(),因为它将对它认为是“true”的任何东西返回true,并将对其他所有东西返回false,就像Brandon指出的那样,你可以执行以下操作。
if (someStringVariable.equals(Boolean.TRUE.toString())) {
...
}
或类似的,
if (someStringVariable.equals(Boolean.FALSE.toString())) {
...
}
boolean status=false;
if (variable.equalsIgnoreCase("true")) {
status=true;
}
仅当字符串为'true'(不区分大小写)时才支持。稍后您可以使用状态变量。
在使用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
}
推荐文章
- 如何在java中格式化持续时间?(如格式H:MM:SS)
- urlencoder .encode(字符串)已弃用,我应该使用什么代替?
- javax.transaction.Transactional vs . org.springframework.transaction.annotation.Transactional
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何找到Java堆大小和内存使用(Linux)?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 我可以将c#字符串值转换为转义字符串文字吗?
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 在c#中解析字符串为日期时间
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠