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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1538755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:57:49  来源:igfitidea点击:

How to convert String object to Boolean Object?

javastringboolean

提问by Suresh Chaganti

How to convert Stringobject to Booleanobject?

如何将String对象转换为Boolean对象?

采纳答案by KLE

Try (depending on what result type you want):

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

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

Advantage:

优势:

  • Boolean: this does not create new instances of Boolean, so performance is better (and less garbage-collection). It reuses the two instances of either Boolean.TRUEor Boolean.FALSE.
  • boolean: no instance is needed, you use the primitive type.
  • Boolean:这不会创建 Boolean 的新实例,因此性能更好(并且垃圾收集更少)。它重用了Boolean.TRUEor的两个实例Boolean.FALSE
  • boolean:不需要实例,你使用原始类型。

The official documentation is in the Javadoc.

官方文档在Javadoc 中



UPDATED:

更新:

Autoboxing could also be used, but it has a performance cost.
I suggest to use it only when you would have to cast yourself, not when the cast is avoidable.

也可以使用自动装箱,但它具有性能成本。
我建议仅在您必须自己施放时才使用它,而不是在可以避免施放时使用。

回答by CJS

Boolean b = Boolean.valueOf(string);

The value of bis true if the string is not a null and equal to true(ignoring case).

b如果字符串不为空且等于true(忽略大小写),则的值为真。

回答by zlajo

You have to be carefull when using Boolean.valueOf(string)or Boolean.parseBoolean(string). The reason for this is that the methods will always return false if the String is not equal to "true" (the case is ignored).

使用Boolean.valueOf(string)Boolean.parseBoolean(string)时必须小心。这样做的原因是如果 String 不等于“true”(忽略大小写),这些方法将始终返回 false。

For example:

例如:

Boolean.valueOf("YES") -> false

Because of that behaviour I would recommend to add some mechanism to ensure that the string which should be translated to a Boolean follows a specified format.

由于这种行为,我建议添加一些机制来确保应转换为布尔值的字符串遵循指定的格式。

For instance:

例如:

if (string.equalsIgnoreCase("true") || string.equalsIgnoreCase("false")) {
    Boolean.valueOf(string)
    // do something   
} else {
    // throw some exception
}

回答by PhiLho

Beside the excellent answer of KLE, we can also make something more flexible:

除了 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");

(inspired by zlajo's answer... :-))

(灵感来自 zlajo 的回答... :-))

回答by Zed

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

回答by Vesco Pro

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

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

This will give you an idea of what to do.

这会让你知道该怎么做。

This is what I get from the Java documentation:

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

Method Detail

parseBoolean

public static boolean parseBoolean(String s)

Parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not nulland is equal, ignoring case, to the string "true".

Parameters:

s- the String containing the boolean representation to be parsed

Returns:the boolean represented by the string argument

Since:1.5

方法细节

parseBoolean

public static boolean parseBoolean(String s)

将字符串参数解析为布尔值。如果字符串参数不null等于字符串“ true” ,则返回的布尔值表示值 true (忽略大小写)。

参数:

s- 包含要解析的布尔表示的字符串

返回:由字符串参数表示的布尔值

自:1.5

回答by Tomislav Boras

This is how I did it:

我是这样做的:

"1##true".contains( string )

"1##true".contains( string )

For my case is mostly either 1 or true. I use hashes as dividers.

对于我的情况,主要是 1 或 true。我使用哈希作为分隔符。

回答by Prateek Singh

you can directly set boolean value equivalent to any string by System class and access it anywhere..

您可以通过 System 类直接设置与任何字符串等效的布尔值并在任何地方访问它。

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

回答by Prateek Singh

To get the boolean value of a String, try this:

要获取字符串的布尔值,请尝试以下操作:

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

If there is an error, it will return null. Example:

如果有错误,它将返回 null。例子:

toBoolean("true"); // Returns true
toBoolean("tr.u;e"); // Returns null

回答by AechoLiu

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

My way to convert string to boolean.

我将字符串转换为布尔值的方法。