how to convert string to bool
string yes no convert into bool true and false
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Yi Rong TanPosted Jan 12, 2015, 1:37 AM
//Let yesNoString be the string containing the "yes" or "no" value
//Let yesNoBoolean be the boolean to be converted to.
if(yesNoString = "yes")
{
YesNoBoolean = true;
}
else if(yesNoString = "no")
{
yesNoBoolean = false;
}
VulpesPosted Jan 11, 2015, 5:24 PM
http://msdn.microsoft.com/en-us/library/system.boolean.tryparse%28v=vs.110%29.aspx
Here's the code to do that for 'Yes' and 'No' values, ignoring case and leading/trailing whitespace:
theLizardPosted Jan 11, 2015, 3:15 PM
String value = "Yes"
bool result = (value.ToLower()=="yes" ? true:false);
or you could create a methode that you could reuse use at will
bool myBoolMethod(String a, string b, bool wantTrueFalse)
{
//compare two strings
bool result;
a = a.ToLower();
b = b.ToLower()
if(wantTrueFalse)
result = (a == b? True : False);
else
result = (a == b? 1 : 0);
}
bool myBoolMethod(String a, bool wantTrueFalse)
{
bool result;
a = a.ToLower();
if(wantTrueFalse)
result = (a == "yes"? True : False);
else
result = (a == "yes"? 1 : 0);
}
String MySurname = "Fred", hisSurname = " Smith"
then you can do bool myanswer = myBoolMethod(MySurname, hisSurname, true);
on return myanswer will be False.
Armin HafizovicPosted Jan 11, 2015, 10:57 AM
string value = "YES"; // or NO
bool result = value.equals("YES", StringComparison.Ordinal);
You could also have an enumeration for your values that you will compare a value against which makes your program more flexible, but for just getting a boolean value depending on the result, this code works just fine.
VulpesPosted Jan 11, 2015, 10:46 AM
string yn = "yes" ; // or "no"
bool b = (yn.ToLower() == "yes");