C #Windows Application将输入字符与字符串进行比较

时间:2015-03-01 08:51:53

标签: c#

我正在使用C#windows窗体。我想在下面的场景中进行比较。

我有两个文本框。第一个文本框(textbox1)是只读的,包含文本:"这是我第一个使用C#的Windows应用程序。"第二个文本框(textbox2)用于用户键入文本与textbox1中的文本相同。如果用户输入了错误的字符,我会在标签中显示字符错误数(lblError)。

示例:如果用户输入""那么lblError应该显示" 1"

谢谢, 曼

1 个答案:

答案 0 :(得分:0)

代码示例:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void CompareWords(string a, string b)
    {
        List<string> diff;
        IEnumerable<string> set1 = a.Split(' ').Distinct();
        IEnumerable<string> set2 = b.Split(' ').Distinct();

        if (set2.Count() > set1.Count())
        {
            diff = set2.Except(set1).ToList();
        }
        else
        {
            diff = set1.Except(set2).ToList();
        }

        labelWrong.Text = ("Wrong words: " + diff.Count());
    }

    private void CompareChars(string a, string b)
    {
        List<string> diff = new List<string>();
        if (a == b) //Same string, no iteration needed.
            lblWrongChars.Text = ("Wrong chars: " + 0);
        if ((a.Length == 0) || (b.Length == 0)) //One is empty
        {
            lblWrongChars.Text = ("Wrong chars: " + (a.Length == 0 ? b.Length : a.Length));
        }
        double maxLen = a.Length > b.Length ? a.Length : b.Length;
        int minLen = a.Length < b.Length ? a.Length : b.Length;
        int sameCharAtIndex = 0;
        for (int i = 0; i < minLen; i++) //Compare char by char
        {
            if (a[i] == b[i])
            {
                diff.Add(b[i].ToString() + ",");
                sameCharAtIndex++;
            }
        }

        lblWrongChars.Text = ("Wrong chars: " + (a.Length - diff.Count()));
    }

    private void txtReadOnly_KeyDown(object sender, KeyEventArgs e)
    {
        string lastchar_inserted = e.KeyValue.ToString();

        if (lastchar_inserted == "32")
        {
            CompareWords(txtReadOnly.Text, txtUserType.Text);
        }

        CompareChars(txtReadOnly.Text, txtUserType.Text);
    }
}