简体   繁体   English

如何检查String中的String值是否为布尔类型?

[英]How to check if String value is Boolean type in Java?

I did a little search on this but couldn't find anything useful. 我对此做了一点搜索,但找不到任何有用的东西。

The point being that if String value is either "true" or "false" the return value should be true. 关键是如果String值为“true”或“false”,则返回值应为true。 In every other value it should be false. 在其他每一个值中都应该是假的。

I tried these: 我试过这些:

String value = "false";
System.out.println("test1: " + Boolean.parseBoolean(value));
System.out.println("test2: " + Boolean.valueOf(value));
System.out.println("test3: " + Boolean.getBoolean(value));

All functions returned false :( 所有函数返回false :(

  • parseBoolean(String) returns true if the String is (case-insensitive) "true", otherwise false 如果String是(不区分大小写)“true”,则parseBoolean(String)返回true,否则返回false
  • valueOf(String) ditto, returns the canonical Boolean Objects valueOf(String)ditto,返回规范的布尔对象
  • getBoolean(String) is a red herring; getBoolean(String)是一个红鲱鱼; it fetches the System property of the given name and compares that to "true" 它获取给定名称的System属性并将其与“true”进行比较

There exists no method to test whether a String encodes a Boolean; 没有方法来测试String是否编码布尔值; for all practical effects, any non-"true"-String is "false". 对于所有实际效果,任何非“true”-String都是“false”。

return "true".equals(value) || "false".equals(value);

Apache commons-lang3 has BooleanUtils with a method toBooleanObject: Apache commons-lang3的BooleanUtils带有toBooleanObject方法:

BooleanUtils.toBooleanObject(String str)

// where: 

BooleanUtils.toBooleanObject(null)    = null
BooleanUtils.toBooleanObject("true")  = Boolean.TRUE
BooleanUtils.toBooleanObject("false") = Boolean.FALSE
BooleanUtils.toBooleanObject("on")    = Boolean.TRUE
BooleanUtils.toBooleanObject("ON")    = Boolean.TRUE
BooleanUtils.toBooleanObject("off")   = Boolean.FALSE
BooleanUtils.toBooleanObject("oFf")   = Boolean.FALSE
BooleanUtils.toBooleanObject("blue")  = null
if ("true".equals(value) || "false".equals(value)) {
  // do something
} else {
  // do something else
}

The methods you're calling on the Boolean class don't check whether the string contains a valid boolean value, but they return the boolean value that represents the contents of the string: put "true" in string, they return true , put "false" in string, they return false . 你在Boolean类上调用的方法不检查字符串是否包含有效的布尔值,但它们返回表示字符串内容的布尔值:在字符串中输入“true”,它们返回true ,put“ false“在字符串中,它们返回false

You can surely use these methods, however, to check for valid boolean values, as I'd expect them to throw an exception if the string contains "hello" or something not boolean. 但是,您肯定可以使用这些方法来检查有效的布尔值,因为如果字符串包含“hello”或者不是布尔值,我希望它们抛出异常。

Wrap that in a Method ContainsBoolString and you're go. 将它包装在一个方法ContainsBoolString ,你就可以了。

EDIT 编辑
By the way, in C# there are methods like bool Int32.TryParse(string x, out int i) that perform the check whether the content can be parsed and then return the parsed result. 顺便说一句,在C#中有一些方法,比如bool Int32.TryParse(string x, out int i) ,它们执行检查是否可以解析内容然后返回解析结果。

int i;
if (Int32.TryParse("Hello", out i))
  // Hello is an int and its value is in i
else
  // Hello is not an int

Benchmarks indicate they are way faster than the following: 基准测试表明它们比以下方式更快:

int i;
try
{
   i = Int32.Parse("Hello");
   // Hello is an int and its value is in i
}
catch
{
   // Hello is not an int
}

Maybe there are similar methods in Java? 也许Java中有类似的方法? It's been a while since I've used Java... 我用过Java已经有一段时间了......

Can also do it by regex: 也可以通过正则表达式来实现:

Pattern queryLangPattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
Matcher matcher = queryLangPattern.matcher(booleanParam);
return matcher.matches();

Actually, checking for a Boolean type in a String (which is a type) is impossible. 实际上,检查String(这是一种类型)中的布尔类型是不可能的。 Basically you're asking how to do a 'string compare'. 基本上你问的是如何进行'字符串比较'。

Like others stated. 和其他人一样。 You need to define when you want to return "true" or "false" (under what conditions). 您需要定义何时返回“true”或“false”(在什么条件下)。 Do you want it to be case(in)sensitive? 你想要它是敏感的吗? What if the value is null? 如果值为null怎么办?

I think Boolean.valueOf() is your friend, javadoc says: 我认为Boolean.valueOf()是你的朋友,javadoc说:

Returns a Boolean with a value represented by the specified String. 返回一个布尔值,其值由指定的String表示。 The Boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true". 如果字符串参数不为null且等于忽略大小写,则返回的布尔值表示值true,返回字符串“true”。

Example: Boolean.valueOf("True") returns true. 示例:Boolean.valueOf(“True”)返回true。
Example: Boolean.valueOf("yes") returns false. 示例:Boolean.valueOf(“yes”)返回false。

String value = "True";
boolean result = value.equalsIgnoreCase("true") ? true : false;

Yes, but, didn't you parse "false"? 是的,但是,你不解析“假”吗? If you parse "true", then they return true. 如果你解析“true”,那么它们返回true。

Maybe there's a misunderstanding: the methods don't test, if the String content represents a boolean value, they evaluate the String content to boolean. 也许有一个误解:方法不测试,如果String内容表示一个布尔值,他们会将String内容计算为boolean。

那么,还要看看org.apache.commons.lang.BooleanUtils #toBoolean(java.lang.String),以及许多其他有用的功能。

return value.equals("false") || value.equals("true");

Something you should also take into consideration is character casing... 你还应该考虑的是字符套管......

Instead of: 代替:

return value.equals("false") || value.equals("true");

Do this: 做这个:

return value.equalsIgnoreCase("false") || value.equalsIgnoreCase("true");

I suggest that you take a look at the Java docs for these methods. 我建议您查看这些方法的Java文档。 It appears that you are using them incorrectly. 您似乎错误地使用它们。 These methods will not tell you if the string is a valid boolean value, but instead they return a boolean, set to true or false, based on the string that you pass in, "true" or "false". 这些方法不会告诉您字符串是否是有效的布尔值,而是根据您传入的字符串“true”或“false”返回布尔值,设置为true或false。

http://www.j2ee.me/javase/6/docs/api/java/lang/Boolean.html http://www.j2ee.me/javase/6/docs/api/java/lang/Boolean.html

Here's a method you can use to check if a value is a boolean: 这是一个可用于检查值是否为布尔值的方法:

boolean isBoolean(String value) {
    return value != null && Arrays.stream(new String[]{"true", "false", "1", "0"})
            .anyMatch(b -> b.equalsIgnoreCase(value));
}

Examples of using it: 使用它的例子:

System.out.println(isBoolean(null)); //false
System.out.println(isBoolean("")); //false
System.out.println(isBoolean("true")); //true
System.out.println(isBoolean("fALsE")); //true
System.out.println(isBoolean("asdf")); //false
System.out.println(isBoolean("01truefalse")); //false

See oracle docs 请参阅oracle docs

public static boolean parseBoolean(String s) {
        return ((s != null) && s.equalsIgnoreCase("true"));
    }
  function isBooleanString(val) {
    if (val === "true" || val === "false"){
      return true
    } else {
      return false
    }
  }
isBooleanString("true") // true
isBooleanString("false") // true

isBooleanString("blabla") // false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM