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


当前回答

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.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
}

您可以直接设置布尔值等价于任何字符串的系统类 并访问它的任何地方..

System.setProperty("n","false");
System.setProperty("y","true");

System.setProperty("yes","true");     
System.setProperty("no","false");

System.out.println(Boolean.getBoolean("n"));   //false
System.out.println(Boolean.getBoolean("y"));   //true   
 System.out.println(Boolean.getBoolean("no"));  //false
System.out.println(Boolean.getBoolean("yes"));  //true

如果你的目标只是将这个字符串变量与“false”或“true”字符串进行比较,而不硬编码这两个值,就像我的情况一样,并且你不想使用Boolean.valueOf(),因为它将对它认为是“true”的任何东西返回true,并将对其他所有东西返回false,就像Brandon指出的那样,你可以执行以下操作。

if (someStringVariable.equals(Boolean.TRUE.toString())) {
...
}

或类似的,

if (someStringVariable.equals(Boolean.FALSE.toString())) {
...
}

使用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