【问题标题】:C# Windows Application compare input character with stringC# Windows 应用程序将输入字符与字符串进行比较
【发布时间】:2015-03-01 08:51:53
【问题描述】:

我正在开发 C# windows 窗体。我想在下面的场景中做一个比较。

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

示例:如果用户键入“the”,则 lblError 应显示“1”

谢谢, 男人

【问题讨论】:

  • 问题是……?
  • 字符串不匹配时是否显示错误?

标签: c#


【解决方案1】:

代码示例:

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);
    }
}

【讨论】:

    猜你喜欢
    • 2021-08-27
    • 2020-07-01
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 2020-04-15
    • 1970-01-01
    相关资源
    最近更新 更多