[英]Matching a string against an array of strings
I have an array of four operations which I want to match against an input string. 我有四个要与输入字符串匹配的操作数组。
My attempt: 我的尝试:
string[] operations = {"add","sub","mul","div"};
string rawInput = Console.ReadLine();
string[] inputs = rawInput.Split(delims,StringSplitOptions.RemoveEmptyEntries);
firstInput = inputs[0].Trim();
foreach (string operation in operations)
{
if (firstInput.Contains(operation))
Console.WriteLine("Valid operation: {0}",operation);
}
As I expected, this prints Valid operation
if I input add, sub, mul or div. 如我所料,如果我输入add,sub,mul或div,这将打印
Valid operation
。
To print a message for invalid input, I have included an else condition like this: 为了输出无效输入的消息,我添加了如下条件:
else
{
Console.WriteLine("Invalid operation: {0}", firstInput);
break;
}
If I input sub
now, I get: 如果我现在输入
sub
,我得到:
Invalid operation: sub
If I remove the break statement and input sub
: 如果我删除break语句并输入
sub
:
Invalid operation: sub
Valid operation: sub
Invalid operation: sub
Invalid operation: sub
How do I modify the logic so that I get correct messages and only once? 如何修改逻辑,以便只收到一次正确的消息?
Look if the first input is in your list of valid operations, instead of the other way around (using LINQ): 查看第一个输入是否在您的有效操作列表中,而不是相反(使用LINQ):
if (operations.Contains(firstInput))
{
Console.WriteLine("Valid operation: {0}", firstInput);
}
else
{
Console.WriteLine("Invalid operation: {0}", firstInput);
}
If iterating over the list, as you have done, this is one option: 如果已经遍历列表,那么这是一种选择:
bool foundValidOP = false;
foreach (string operation in operations)
{
if (firstInput.Equals(operation, StringComparison.InvariantCultureIgnoreCase))
{
foundValidOP = true;
break;
}
}
if (foundValidOP)
{
Console.WriteLine("Valid operation: {0}", firstInput);
}
else
{
Console.WriteLine("Invalid operation: {0}", firstInput);
}
Your foreach
loop iterates over each of the entries in operations
, so your logic is incorrect because it will break out of the loop if the input doesn't match the first element in operations
(namely, "add"
). 您的
foreach
循环会遍历operations
每个条目,因此您的逻辑是不正确的,因为如果输入与operations
中的第一个元素(即"add"
)不匹配,则它将超出循环。 You really want to break out of the loop if a valid operation is found and otherwise keep scanning. 如果发现有效操作,您确实想跳出循环,否则继续扫描。 Here is some sample code:
这是一些示例代码:
bool validOperation = false;
foreach (string operation in operations)
{
if (firstInput.Contains(operation))
{
Console.WriteLine("Valid operation: {0}",operation);
validOperation = true;
break;
}
}
if (!validOperation)
{
Console.WriteLine("Invalid operation: {0}", firstInput);
}
You can try this: 您可以尝试以下方法:
string[] operations = { "add", "sub", "mul", "div" };
var firstInput = "sudb";
var x = operations.SingleOrDefault(o => o == firstInput);
if (x != null)
Console.WriteLine("Valid:" + x);
else
Console.WriteLine("Invalid:" + firstInput);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.