如何检查不同/不等数组长度的数组中的字符串匹配?

时间:2014-07-07 04:20:10

标签: c# arrays match

我试图从数组中获取匹配的字符串,但是,只有当字符串的长度相等时,它们才匹配。我使用split将字符串变为数组。

例如,从数据库中取出字符串“The Quick Brown Fox”将匹配“The Quick Brown Fox”的用户输入,而不是“The Quick Brown Fox Jumps”

我想将字符串“The Quick Brown Fox”与“The Quick Brown Fox Jumps”相匹配,将4个字(The Quick Brown Fox)视为正确,将“Jumps”视为错误。另外,如果它比WordsFromDatabaseSplit字符串短,我需要匹配EnteredWordsSplit。

        if (WordsFromDatabaseSplit.Length == EnteredWordsSplit.Length)
        {

            for (int i = 0; i < WordsFromDatabaseSplit.Length; i++)
            {
                if (WordsFromDatabaseSplit[i] == EnteredWordsSplit[i])
                {
                    correct++;
                }
                else
                {
                    wrong++;
                }
            }
            textBoxEnter.Text = "";
        }
        else
        {
            //code for matching
            textBoxEnter.Text = "";
        }

2 个答案:

答案 0 :(得分:0)

试试这个

    public int ReturnRightCount(out int wrongCount)
    {
        var dbString = "The Quick Brown Fox";
        var inputString = "The Quick Brown Fox Jumps";
        var returnRight = 0;
        wrongCount = 0;

        var WordsFromDatabaseSplit = dbString.Split(' ');
        var EnteredWordsSplit = inputString.Split(' ');

        if (WordsFromDatabaseSplit.Length > EnteredWordsSplit.Length)
        {
            wrongCount = 0;
           return 0;
        }

        for (int i = 0; i < WordsFromDatabaseSplit.Length; i++)
        {
            if (WordsFromDatabaseSplit[i].Equals(EnteredWordsSplit[i],StringComparison.OrdinalIgnoreCase))
            {
                returnRight ++;
            }
            else
            {
                wrongCount++;
            }
        }

        return returnRight;
    }
}

答案 1 :(得分:0)

根据建议您可以使用Contains来更轻松地进行匹配。现在我假设即使Database String长于Input StringInput String也可以找到Database String

String dbString = "The Quick Brown Fox";
String inputString = "The Quick Brown Fox Jumps";
int correct=0, wrong=0;

if (inputString.Contains(dbString))
   {
      correct = dbString.Split(' ').Count(); // In our example the result is 4
      wrong = inputString.Split(' ').Count() - correct; // In our example the result is 1
   }