【问题标题】:Can't count words from richtextbox to label?无法计算来自richtextbox 的单词到标签?
【发布时间】:2012-05-09 16:22:48
【问题描述】:

我不确定这里出了什么问题,但我正在尝试计算富文本框中的单词,并用标签显示它。

我在选项卡控件中放置了一个富文本框,这样我就可以拥有一个选项卡式文本框。这似乎让这件事变得更难了

这也不是整个程序,我把与richtextbox和word counter相关的部分拿走了

任何帮助表示赞赏:)

    public RichTab()
    {
        InitializeComponent();
        TabPage tp = new TabPage("Document");
        RichTextBox rtb = new RichTextBox();
        rtb.Dock = DockStyle.Fill;
        tp.Controls.Add(rtb);
        tabControl1.TabPages.Add(tp);
        WordCount();
    }

    public RichTextBox RTTB()
    {
        RichTextBox rtb = null;
        TabPage tp = tabControl1.SelectedTab;
        if (tp != null)
        {
            rtb = tp.Controls[0] as RichTextBox;
        }
        return rtb;
    }

    private void WordCount()
    {
        MatchCollection wordColl = Regex.Matches(RTTB().Text, @"[\W]+");
        label2.Text = wordColl.Count.ToString();   
    }

【问题讨论】:

  • 您已经在标签上放置了一个 RTB,那么该 RTB 的名称是什么?

标签: c# textbox richtextbox word-count


【解决方案1】:

我可能只是连接 RichTextBox 的 TextChanged 事件,然后数那里的字数:

rtb.TextChanged += rtb_TextChanged;

然后数单词(使用 Giorgio Minardi 的正则表达式):

private void rtb_TextChanged(object sender, EventArgs e) {
  label2.Text = Regex.Matches(((RichTextBox)sender).Text, @"[\S]+").Count.ToString();
}

【讨论】:

    【解决方案2】:

    真正的问题是什么? 这是一个计算单词的简单例程:

    [Test]
    public void CountWords()
    {
        const string sample = "How you doing today ?";
        MatchCollection collection = Regex.Matches(sample, @"[\S]+");
        var numberOfWords = collection.Count;
        //numberOfWords is 5
        Assert.IsTrue(numberOfWords == 5);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多