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


当前回答

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

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

非常方便!

其他回答

boolean b = string.equalsIgnoreCase("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的回答启发……: -))

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

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

非常方便!

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

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

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

这会让你知道该怎么做。

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

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