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


当前回答

要获得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

其他回答

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

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

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

要获得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

我是这样做的:

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

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

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

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