在if语句中实现字符串和OR函数(||)

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)

其他问题:

  1. 双==签名
  2. 去掉 ; 在if语句的末尾

为了提高可读性:

string[] allowedValues = { "+", "1", "2" };
if (allowedValues.Contains(justThePlus)) {
Run Code Online (Sandbox Code Playgroud)


Cur*_*urt 6

OR语句需要一个条件:

if (justThePlus == "+" || justThePlus == "1" || ....)
Run Code Online (Sandbox Code Playgroud)

也:

  • 使用==而不是=字符串比较
  • 从if语句的末尾删除分号.


Ste*_*lis 6

您可以使用包含的数组:

if (new[] { "+" ,  "1" ,  "2" ,  "3" ,  "4" ,  "5" ,  "6" , "7" ,  "8" ,  "9" , "0" }.Contains(justThePlus));
{

}
Run Code Online (Sandbox Code Playgroud)