如何将字符串对象转换为布尔对象?
当前回答
boolean b = string.equalsIgnoreCase("true");
其他回答
要获得String的布尔值,请尝试以下方法:
public boolean toBoolean(String s) {
try {
return Boolean.parseBoolean(s); // Successfully converted String to boolean
} catch(Exception e) {
return null; // There was some error, so return null.
}
}
如果有错误,它将返回null。 例子:
toBoolean("true"); // Returns true
toBoolean("tr.u;e"); // Returns null
为什么不用正则表达式呢?
public static boolean toBoolean( String target )
{
if( target == null ) return false;
return target.matches( "(?i:^(1|true|yes|oui|vrai|y)$)" );
}
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'(不区分大小写)时才支持。稍后您可以使用状态变量。
尝试(取决于你想要的结果类型):
Boolean boolean1 = Boolean.valueOf("true");
boolean boolean2 = Boolean.parseBoolean("true");
优势:
Boolean:它不会创建新的Boolean实例,因此性能更好(并且垃圾收集更少)。它重用任意一个布尔值的两个实例。TRUE或布尔值。false。 布尔型:不需要实例,使用基本类型。
官方文档在Javadoc中。
更新:
也可以使用自动装箱,但它有性能成本。 我建议只在你不得不打石膏的时候使用它,而不是在可以避免打石膏的时候。
推荐文章
- 如何在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中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠