Just for neatness sake I was wondering, whether it's possible to cast Y or N to a bool? Something like this;
bool theanswer = Convert.ToBoolean(input);
The long version;
bool theanswer = false;
switch开发者_JAVA技巧 (input)
{
case "y": theanswer = true; break;
case "n": theanswer = false; break
}
No, there's nothing built in for this.
However, given that you want to default to false, you can just use:
bool theAnswer = (input == "y");
(The bracketing there is just for clarity.)
You may want to consider making it case-insensitive though, given the difference between the text of your question and the code you've got. One way of doing this:
bool theAnswer = "y".Equals(input, StringComparison.OrdinalIgnoreCase);
Note that using the specified string comparison avoids creating a new string, and means you don't need to worry about cultural issues... unless you want to perform a culture-sensitive comparison, of course. Also note that I've put the literal as the "target" of the method call to avoid NullReferenceException
being thrown when input
is null
.
bool theanswer = input.ToLower() == "y";
As suggested by Jon, there's nothing inbuilt like this. The answer posted by John gives you a correct way of doing. Just for more clarification, you can visit:
http://msdn.microsoft.com/en-us/library/86hw82a3.aspxlink text
Create an extension method for string that does something similar to what you specify in the second algorithm, thus cleaning up your code:
public static bool ToBool(this string input)
{
// input will never be null, as you cannot call a method on a null object
if (input.Equals("y", StringComparison.OrdinalIgnoreCase))
{
return true;
}
else if (input.Equals("n", StringComparison.OrdinalIgnoreCase))
{
return false;
}
else
{
throw new Exception("The data is not in the correct format.");
}
}
and call the code:
if (aString.ToBool())
{
// do something
}
how about this.
bool theanswer = input.Equals("Y", StringComparison.OrdinalIgnoreCase);
or yet safer version.
bool theanswer = "Y".Equals(input, StringComparison.OrdinalIgnoreCase);
Or this?
bool CastToBoolean(string input)
{
return input.Equals("Y", StringComparison.OrdinalIgnoreCase);
}
I faced the same problem but solved other way.
bool b=true;
decimal dec;
string CurLine = "";
CurLine = sr.ReadLine();
string[] splitArray = CurLine.Split(new Char[] { '=' });
splitArray[1] = splitArray[1].Trim();
if (splitArray[1].Equals("Y") || splitArray[1].Equals("y")) b = true; else b = false;
CurChADetails.DesignedProfileRawDataDsty1.Commen.IsPad = b;
DotNetPerls has a handy class for parsing various string bools.
/// <summary>
/// Parse strings into true or false bools using relaxed parsing rules
/// </summary>
public static class BoolParser
{
/// <summary>
/// Get the boolean value for this string
/// </summary>
public static bool GetValue(string value)
{
return IsTrue(value);
}
/// <summary>
/// Determine whether the string is not True
/// </summary>
public static bool IsFalse(string value)
{
return !IsTrue(value);
}
/// <summary>
/// Determine whether the string is equal to True
/// </summary>
public static bool IsTrue(string value)
{
try
{
// 1
// Avoid exceptions
if (value == null)
{
return false;
}
// 2
// Remove whitespace from string
value = value.Trim();
// 3
// Lowercase the string
value = value.ToLower();
// 4
// Check for word true
if (value == "true")
{
return true;
}
// 5
// Check for letter true
if (value == "t")
{
return true;
}
// 6
// Check for one
if (value == "1")
{
return true;
}
// 7
// Check for word yes
if (value == "yes")
{
return true;
}
// 8
// Check for letter yes
if (value == "y")
{
return true;
}
// 9
// It is false
return false;
}
catch
{
return false;
}
}
}
Is called by;
BoolParser.GetValue("true")
BoolParser.GetValue("1")
BoolParser.GetValue("0")
This could probably be further improved by adding a parameter overload to accept an object.
Wonea gave an "IsTrue" source example from DotNetPerls. Here are two shorter versions of it:
public static bool IsTrue(string value)
{
// Avoid exceptions
if (value == null)
return false;
// Remove whitespace from string and lowercase it.
value = value.Trim().ToLower();
return value == "true"
|| value == "t"
|| value == "1"
|| value == "yes"
|| value == "y";
}
OR:
private static readonly IReadOnlyCollection<string> LOWER_TRUE_VALUES = new string[] { "true", "t", "1", "yes", "y" };
public static bool IsTrue(string value)
{
return value != null
? LOWER_TRUE_VALUES.Contains(value.Trim().ToLower())
: false;
}
Heck, if you want to get real short (and ugly), you can collapse that down to two lines like this:
private static readonly IReadOnlyCollection<string> LOWER_TRUE_VALUES = new string[] { "true", "t", "1", "yes", "y" };
public static bool IsTrue(string value) => value != null ? LOWER_TRUE_VALUES.Contains(value.Trim().ToLower()) : false;
class Program
{
void StringInput(string str)
{
string[] st1 = str.Split(' ');
if (st1 != null)
{
string a = str.Substring(0, 1);
string b=str.Substring(str.Length-1,1);
if(
a=="^" && b=="^"
|| a=="{" && b=="}"
|| a=="[" && b=="]"
||a=="<" && b==">"
||a=="(" && b==")"
)
{
Console.Write("ok Formate correct");
}
else
{
Console.Write("Sorry incorrect formate...");
}
}
}
static void Main(string[] args)
{
ubaid: ;
Program one = new Program();
Console.Write("For exit Press N ");
Console.Write("\n");
Console.Write("Enter your value...=");
string ub = Console.ReadLine();
if (ub == "Y" || ub=="y" || ub=="N" || ub=="n" )
{
Console.Write("Are your want to Exit Y/N: ");
string ui = Console.ReadLine();
if (ui == "Y" || ui=="y")
{
return;
}
else
{
goto ubaid;
}
}
one.StringInput(ub);
Console.ReadLine();
goto ubaid;
}
}
精彩评论