在数组中找不到某些值

时间:2013-05-14 15:52:40

标签: 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";
}

1 个答案:

答案 0 :(得分:4)

您的代码无效的原因在于no数组的内容:它包含单个字母的字符串"n"。这个字符串是

no.Any( input.Contains )

评估True包含字母'n'的任何输入字符串。

要解决此问题,您可以将walk的支票移至if / then / else链的顶部。但是,解决方案不会过于健壮:"yellow"将被归类为"yes""cat"将归为"clear",依此类推。