将字符串与字符串数组进行匹配

本文关键字:字符串 数组 | 更新日期: 2023-09-27 18:17:31

我有一个包含四个操作的数组,我想将它们与输入字符串进行匹配。

我的尝试:

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条件,如下所示:

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

我如何修改逻辑,使我得到正确的消息,而且只有一次?

将字符串与字符串数组进行匹配

查看第一个输入是否在有效操作列表中,而不是相反(使用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);
}

您的foreach循环遍历operations中的每个条目,因此您的逻辑是不正确的,因为如果输入与operations(即"add")中的第一个元素不匹配,它将跳出循环。如果找到了有效的操作,您确实希望跳出循环,否则继续扫描。下面是一些示例代码:

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

你可以试试:

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