匹配字符串数组的字符串

时间:2011-12-10 19:42:45

标签: c#

我有一个包含四个操作的数组,我希望与输入字符串匹配。

我的尝试:

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);
}

正如我所料,如果输入add,sub,mul或div,则打印Valid operation

要打印无效输入的消息,我已经包含了这样的其他条件:

else
{
    Console.WriteLine("Invalid operation: {0}", firstInput);
    break;
}

如果我现在输入sub,我会:

Invalid operation: sub

如果我删除了break语句并输入sub

Invalid operation: sub
Valid operation: sub
Invalid operation: sub
Invalid operation: sub

如何修改逻辑以便我只收到一次正确的消息?

3 个答案:

答案 0 :(得分:3)

查看第一个输入是否在您的有效操作列表中,而不是相反(使用LINQ):

if (operations.Contains(firstInput))
{
  Console.WriteLine("Valid operation: {0}", firstInput);
}
else
{
  Console.WriteLine("Invalid operation: {0}", firstInput);
}

如果按照您的方式迭代列表,这是一个选项:

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);
}

答案 1 :(得分:2)

你的foreach循环遍历operations中的每个条目,因此你的逻辑是不正确的,因为如果输入与{{1中的第一个元素不匹配,它将突破循环(即operations)。如果找到有效的操作,你真的想要打破循环,否则继续扫描。以下是一些示例代码:

"add"

答案 2 :(得分:1)

你可以试试这个:

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);