在if语句中实现字符串和OR函数(||)
本文关键字:OR 函数 字符串 if 语句 实现 | 更新日期: 2023-09-27 17:49:44
我目前正试图使一个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();
部分,"justThePlus = "+" ||"目前有一个红色下划线,描述为,
"运算符'||'不能用于'string'和'string'类型的操作数"字符串"。
如果我不能使用OR语句,什么是与字符串工作的替代方案?
你就快成功了:
if (justThePlus == "+" || justThePlus =="1" || justThePlus =="2")
其他问题:- Double == sign
- 删除;if语句的结尾
提高可读性:
string[] allowedValues = { "+", "1", "2" };
if (allowedValues.Contains(justThePlus)) {
OR语句两边都需要一个条件:
if (justThePlus == "+" || justThePlus == "1" || ....)
也:
- 使用
==
代替=
进行字符串比较 - 去掉if语句末尾的分号
你可以使用一个数组包含:
if (new[] { "+" , "1" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" , "0" }.Contains(justThePlus));
{
}
这是一个不同的逻辑来实现相同的。
var validChars= "+1234567890" ;
if(justThePlus.Length==1 && validChars.IndexOf(justThePlus)>=0)
{
}
我觉得你把这件事弄得太难了。
// Ensures the string has 9 digits and optionally starts with a "+"
Regex regex = new Regex(@"^('+)?([0-9]{9})");
string input;
while (!regex.IsMatch(input))
{
Console.Write("Please enter your phone number: ");
input = Console.ReadLine();
}
||
运算符期望两个操作数都是bool
值。该操作数在两个操作数之间执行逻辑或运算。
可以看到,对string
操作数使用此操作符是没有意义的。
你可以把你所有的数字和+
符号放在List<string>
中,你可以用Contains
和Any
方法检查它,如;
var listOfNumbersAndPlus = new List<string>(){"+", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};
if(listOfNumbersAndPlus.Any(justThePlus.Contains))
您可以使用Regex来验证输入
var input = "+12345678";
var pattern = @"'+'d{8}"; // matches number, which is at leas 8-digit long and starts with '+' sign
var isValidNumber = Regex.IsMatch(input, pattern);
电话号码可以由user以多种不同的格式表示,例如:
+1(555)123-45-67
8 555 123 45 67
+75551234567
所以我强烈建议你使用正则表达式;在你的例子中,它可以是
https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s03.html 例如 Console.Write("Please enter your phone number: ");
string input = Console.ReadLine();
//TODO: you may want to update/change this pattern
String pattern = "^'+(?:[0-9] ?){6,14}[0-9]$";
Boolean isNumberValid = Regex.IsMatch(input, pattern);
那么,如果input
字符串是一个有效的字符串,您可以在Linq:
// Standard phone number representation: e.g. 155512345678
String stdNumber = new String(input.Where(ch => ch >= '0' && ch <= '9').ToArray());
您的问题已得到直接回答(justThePlus ==" +" || justThePlus =="1"…)这里有一个更有效的方法来做同样的事情:
switch (justThePlus)
{
case "+" :
case "0" :
case "1" :
case "2" :
case "3" :
case "4" :
case "5" :
case "6" :
case "7" :
case "8" :
case "9" :
// ???
break;
default :
// ???
break;
}