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


当前回答

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

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

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

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

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

我是这样做的:

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

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