Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert a string to a bool

I have a string that can be either "0" or "1", and it is guaranteed that it won't be anything else.

So the question is: what's the best, simplest and most elegant way to convert this to a bool?

like image 945
Sachin Kainth Avatar asked Mar 16 '12 18:03

Sachin Kainth


People also ask

Can you convert a string to a bool in C++?

Using equality operator Finally, for a task as simple as this is, we can write our own validator using the equality operator, as shown below. But like the previous function, this also sets the boolean value to false on any invalid input. That's all about converting a string to bool value in C++.

Can we convert string to boolean in C#?

OP, you can convert a string to type Boolean by using any of the methods stated below: string sample = "True"; bool myBool = bool. Parse(sample); // Or bool myBool = Convert. ToBoolean(sample);

How can I convert a string to boolean in Javascript?

The easiest way to convert string to boolean is to compare the string with 'true' : let myBool = (myString === 'true'); For a more case insensitive approach, try: let myBool = (myString.

Can you convert a string to a boolean in Python?

Use the bool() Function to Convert String to Boolean in Python. We can pass a string as the argument of the function to convert the string to a boolean value. This function returns true for every non-empty argument and false for empty arguments.


1 Answers

Quite simple indeed:

bool b = str == "1"; 
like image 78
Kendall Frey Avatar answered Sep 21 '22 00:09

Kendall Frey