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


尝试(取决于你想要的结果类型):

Boolean boolean1 = Boolean.valueOf("true");
boolean boolean2 = Boolean.parseBoolean("true");

优势:

Boolean:它不会创建新的Boolean实例,因此性能更好(并且垃圾收集更少)。它重用任意一个布尔值的两个实例。TRUE或布尔值。false。 布尔型:不需要实例,使用基本类型。

官方文档在Javadoc中。


更新:

也可以使用自动装箱,但它有性能成本。 我建议只在你不得不打石膏的时候使用它,而不是在可以避免打石膏的时候。

Boolean b = Boolean.valueOf(string);

如果字符串不是空值并且等于true(忽略大小写),则b的值为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
}

除了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的回答启发……: -))

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

访问http://msdn.microsoft.com/en-us/library/system.boolean.parse.aspx

这会让你知道该怎么做。

这是我从Java文档中得到的:

方法的细节 parseBoolean parseBoolean(String s) 将字符串参数解析为布尔值。如果字符串参数不为空,返回的布尔值表示true,并且忽略大小写,等于字符串"true"。 参数: s -包含要解析的布尔表示的字符串 返回:由字符串参数表示的布尔值 自: 1.5

我是这样做的:

“1 # #真”。Contains(字符串)

因为我的情况大多是1或真。我使用散列作为分隔符。

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

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

要获得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 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.");
    }

我把字符串转换成布尔值的方法。

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

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

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

在2018年1月,最好的方法是使用apache的BooleanUtils.toBoolean。

这将把任何布尔值如字符串转换为布尔值,例如Y, yes, true, N, no, false等。

非常方便!

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

import io.thedocs.soyuz.to;

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

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

boolean status=false;
if (variable.equalsIgnoreCase("true")) {
   status=true;  
   }

仅当字符串为'true'(不区分大小写)时才支持。稍后您可以使用状态变量。

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

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

或类似的,

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