Ale*_*lex 2 c# string if-statement
我目前正在尝试创建一个if语句来验证字符串.这是我现在所拥有的.
Console.Write("Please enter your phone number: ");
string input = Console.ReadLine();
if (input.Length < 9)
{
Console.WriteLine("Phone number is not valid, please try again.");
}
string everythingButThePlus = input.Substring(1);
string justThePlus = input.Substring(0, 1);
if (justThePlus = "+" || "1" || "2" || "3" || "4" || "5" || "6" || "7" || "8" || "9" || "0") ;
{
}
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
部分,"justThePlus ="+"||" 目前有一个红色下划线,描述是,
"运营商'||' 不能应用于'string'和'string'类型的操作数.
如果我不能使用OR语句,那么什么是与字符串一起使用的替代方法?
Rvd*_*vdK 12
你快到了:
if (justThePlus == "+" || justThePlus =="1" || justThePlus =="2")
Run Code Online (Sandbox Code Playgroud)
其他问题:
为了提高可读性:
string[] allowedValues = { "+", "1", "2" };
if (allowedValues.Contains(justThePlus)) {
Run Code Online (Sandbox Code Playgroud)
OR语句需要一个条件:
if (justThePlus == "+" || justThePlus == "1" || ....)
Run Code Online (Sandbox Code Playgroud)
也:
==而不是=字符串比较您可以使用包含的数组:
if (new[] { "+" , "1" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" , "0" }.Contains(justThePlus));
{
}
Run Code Online (Sandbox Code Playgroud)