如何将字符串对象转换为布尔对象?


当前回答

boolean b = string.equalsIgnoreCase("true");

其他回答

为什么不用正则表达式呢?

public static boolean toBoolean( String target )
{
    if( target == null ) return false;
    return target.matches( "(?i:^(1|true|yes|oui|vrai|y)$)" );
}
boolean b = string.equalsIgnoreCase("true");
Boolean b = Boolean.valueOf(string);

如果字符串不是空值并且等于true(忽略大小写),则b的值为true。

我们创建了soyuz-to库来简化这个问题(将X转换为Y),它只是一组类似问题的SO答案。使用库来解决如此简单的问题可能有些奇怪,但它确实有助于解决许多类似的情况。

import io.thedocs.soyuz.to;

Boolean aBoolean = to.Boolean("true");

请检查它-它非常简单,有很多其他有用的功能

使用Apache Commons库中的BooleanUtils类:

String[] values= new String[]{"y","Y","n","N","Yes","YES","yes","no","No","NO","true","false","True","False","TRUE","FALSE",null};
for(String booleanStr : values){
    System.out.println("Str ="+ booleanStr +": boolean =" +BooleanUtils.toBoolean(booleanStr));
}

结果:

Str =N: boolean =false
Str =Yes: boolean =true
Str =YES: boolean =true
Str =yes: boolean =true
Str =no: boolean =false
Str =No: boolean =false
Str =NO: boolean =false
Str =true: boolean =true
Str =false: boolean =false
Str =True: boolean =true
Str =False: boolean =false
Str =TRUE: boolean =true
Str =FALSE: boolean =false
Str =null: boolean =false