简体   繁体   中英

How to convert String value to Boolean value in Java

I have String values which return via Java Socket. The String values looks like below

<command valid="true" /> 
    and 
<command name="LoadDocument" executed="true" />

I need to read this Strings and store "valid" and "executed" parts values into Boolean variable. ("valid" and "executed" parts can be true or false). I tried following solution,

String str = "<command valid=\"true\" />"; // stored command in a String variable
boolean bool = Boolean.parseBoolean(str); // pass it as an argument

but bool value is always false. how can I do this?

You can do this safely. First, you have to make sure the string is not null and its value is Here, the case is ignored. So, "true" or "TRUE" will return boolean true otherwise false

String str = "true";
String str1 = "ok";
boolean bool = Boolean.parseBoolean(str);
System.out.println(bool);
boolean bool1 = Boolean.parseBoolean(str1);
System.out.println(bool1);

result

true
false

I think you can use regexp regex101.com :

private static final String REGEXP = "<command.+(?:valid|executed)=\"(?<val>[^\"]+)\"\\s*\\/>";
private static final Pattern PATTERN = Pattern.compile(REGEXP);

public static boolean isValidOrExecuted(String str) {
    Matcher matcher = PATTERN.matcher(str);
    boolean matches = matcher.matches();
    return matches && Boolean.parseBoolean(matcher.group("val"));
}

Demo:

System.out.println(isValidOrExecuted("<command valid=\"true\" />"));                            // true
System.out.println(isValidOrExecuted("<command valid=\"false\" />"));                           // false
System.out.println(isValidOrExecuted("<command name=\"LoadDocument\" executed=\"true\" />"));   // true
System.out.println(isValidOrExecuted("<command name=\"LoadDocument\" executed=\"false\" />"));  // false

String valid = "true"; String executed = "true";

Boolean validParsed = Boolean.parseBoolean(valid); Boolean executedParsed = Boolean.parseBoolean(executed);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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