gpt4 book ai didi

c# - 将字符串与字符串数组进行匹配

转载 作者:行者123 更新时间:2023-12-02 15:04:36 25 4
gpt4 key购买 nike

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

我的尝试:

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,我会得到:

无效操作: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);
}

关于c# - 将字符串与字符串数组进行匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8459338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com