c# - 在数组中找不到某些值

标签 c# arrays

我有一个字符串数组,每个字符串都是用 "<x> <y>" 的形式构建的.如果y'n' 开始,看来我的程序找不到它。

所以,不起作用的字符串是。

"w north",
"w n",
"walk n",
"walk north"

你能帮忙解释一下原因吗?

string[] next = { "next", "ne", "nx", "nxt" };
string[] yes = { "yes", "y" };
string[] no = { "no", "n" };
string[] clear = { "clear", "c" };
string[] help = { "help", "h" };
string[] walk = 
        { 
            "w north", 
            "w south",
            "w west",
            "w east",
            "w n",
            "w s",
            "w w",
            "w e",
            "walk north",
            "walk south",
            "walk west",
            "walk east" ,
            "walk n",
            "walk s",
            "walk w",
            "walk e"
        };

//Checks if any input match the arrays
public string Input(string input)
{
    input = input.ToLower();
    if (next.Any(input.Contains))
    {
        return "next";
    }
    else if (yes.Any(input.Contains))
    {
        return "yes";
    }
    else if (no.Any(input.Contains))
    {
        return "no";
    }
    else if (clear.Any(input.Contains))
    {
        return "clear";
    }
    else if (help.Any(input.Contains))
    {
        return "help";
    }
    else if (walk.Any(input.Contains))
    {
        MessageBox.Show("test input");
        Location C_locations = new Location();
        C_locations.Change_location(input);
        return "walk";
    }
    else
    {
        return "not found";
    }
}

字符串:"w north" , "w n" , "walk n""walk north" ,应该运行这部分代码:

else if (walk.Any(input.Contains))
{
    MessageBox.Show( "test input" );
    Location C_locations = new Location();
    C_locations.Change_location( input );
    return "walk";
}

最佳答案

您的代码不起作用的原因在于您的no 数组的内容:它包含一个单字母字符串"n"。正是这个字符串使得

no.Any( input.Contains )

对于包含字母 'n' 的任何输入字符串,求值为 True

为了解决这个问题,您可以将 walk 的检查移动到 if/then/ 的顶部else 链。但是,该解决方案不会过于稳健:"yellow" 将被归类为 "yes""cat" 将变为 “清除”,等等。

关于c# - 在数组中找不到某些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16547638/

相关文章:

c# - AutoMapper map 子属性也定义了 map

c# - 提交表单后如何显示提交成功消息

c# - 如何先用msbuild建立依赖项目

arrays - Swift 根据总值(value)将数组分割成 block

c# - switch 语句中的变量初始化问题

c# - 表没有得到更新,当使用 executeNonquery

php - array_values 递归 php

C 程序问题 : scanf isn't working properly

java - 如何创建一个包含 "n"个随机整数的数组?

php - 如何获取数组的父键