给定一个字符串str ,任务是将给定的字符串转换为其布尔值。
Boolean datatype consists of only two values: true and false. If the string is true (ignoring case), the Boolean equivalent will be true, else false.
例子:
Input: str = “true”
Output: true
Explanation: The boolean equivalent of true is true itself.
Input: str = “false”
Output: false
Explanation: The boolean equivalent of false is false itself.
Input: str = “yes”
Output: false
Explanation: The boolean equivalent of yes is false since the given value is not equal to true.
将字符串转换为其布尔值的方法如下:
方法一:
- 使用Boolean.parseBoolean()方法。这是将字符串转换为布尔值的最常用方法。
- 此方法用于将给定字符串转换为其原始布尔值。
- 如果给定的字符串包含值true (忽略字符串),则此方法返回true ,如果字符串包含除true之外的任何其他值,则该方法返回false 。
句法:
boolean boolValue = Boolean.parseBoolean(String str)
下面是上述方法的实现:
Java
class GFG {
// Function to convert a string
// to its boolean value
public static boolean
stringToBoolean(String str)
{
// convert a given string to
// its primitive boolean value
// using parseBoolean() method
boolean b1
= Boolean.parseBoolean(str);
// returns primitive boolean value
return b1;
}
// Driver code
public static void main(String args[])
{
// Given String str
String str = "yes";
// print the result
System.out.println(
stringToBoolean(str));
// Given String str
str = "true";
// print the result
System.out.println(
stringToBoolean(str));
// Given String str
str = "false";
// print the result
System.out.println(
stringToBoolean(str));
}
}
Java
class GFG {
// Function to convert a string
// to its boolean object
public static boolean
stringToBoolean(String str)
{
// convert a given string to
// its boolean object using
// valueOf() method
boolean b1 = Boolean.valueOf(str);
// returns boolean object
return b1;
}
// Driver code
public static void main(String args[])
{
// Given String str
String str = "yes";
// print the result
System.out.println(
stringToBoolean(str));
// Given String str
str = "true";
// print the result
System.out.println(
stringToBoolean(str));
// Given String str
str = "false";
// print the result
System.out.println(
stringToBoolean(str));
}
}
false
true
false
方法二:
- 使用 Boolean.valueOf() 方法。
- 它类似于 Boolean.parseBoolean() 方法,但它返回一个布尔对象而不是原始布尔值。
句法:
boolean boolValue = Boolean.valueOf(String str)
下面是上述方法的实现:
Java
class GFG {
// Function to convert a string
// to its boolean object
public static boolean
stringToBoolean(String str)
{
// convert a given string to
// its boolean object using
// valueOf() method
boolean b1 = Boolean.valueOf(str);
// returns boolean object
return b1;
}
// Driver code
public static void main(String args[])
{
// Given String str
String str = "yes";
// print the result
System.out.println(
stringToBoolean(str));
// Given String str
str = "true";
// print the result
System.out.println(
stringToBoolean(str));
// Given String str
str = "false";
// print the result
System.out.println(
stringToBoolean(str));
}
}
false
true
false
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live