什么是最有效的方法来计算所有的话在一个RichTextBox? [英] What is the most efficient way to count all of the words in a richtextbox?

查看:117
本文介绍了什么是最有效的方法来计算所有的话在一个RichTextBox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个文本编辑器,并需要提供现场字数。现在,我使用这个扩展方法:

I am writing a text editor and need to provide a live word count. Right now I am using this extension method:

 public static int WordCount(this string s)
    {
        s = s.TrimEnd();
        if (String.IsNullOrEmpty(s)) return 0;
        int count = 0;
        bool lastWasWordChar = false;
        foreach (char c in s)
        {
            if (Char.IsLetterOrDigit(c) || c == '_' || c == '\'' || c == '-')
            {
                lastWasWordChar = true;
                continue;
            }
            if (lastWasWordChar)
            {
                lastWasWordChar = false;
                count++;
            }
        }
        if (!lastWasWordChar) count--;
        return count + 1;
    }



我有它设置,以便字数在RichTextBox中的文本每十运行第二(如果选择开始从它上次的时间的方法不同运行)。问题是,该字计数工作很长的文件时,得到缓慢。为了解决这个问题,我想具有字数只对当前运行段,记录了字,每次数和作比较什么字计数字数跑了最后一次。然后,它会增加两者之间的差的总字数。
这样做会造成许多并发症(如果用户贴,如果用户删除了一个段落,等。)
这是一个逻辑的方法去改善我的话算不算?或者是有什么,我不知道这将使它更好

I have it set so that the word count runs on the richtextbox's text every tenth of a second (if the selection start is different from what it was last time the method ran). The problem is that the word count gets slow when working on very long files. To solve this I am thinking about having the word count only run on the current paragraph, recording the word count each time and comparing it against what the word count was last time the word count ran. It would then add the difference between the two to the total word count. Doing this would cause many complications (if the user pastes, if the user deletes a paragraph, ect.) Is this a logical way to go about improving my word count? Or is there something that I don't know about which would make it better?

编辑:
将它的工作运行在不同的线程的字数?我不知道很多有关线程,将研究

Would it work to run the word count on a different thread? I don't know much about threading, will research.

样例文本,我用:

推荐答案

您可以做一个简单的字数基于空白:

You could do a simpler word count based on white-space:

public static int WordCount(this string s)
{
  return s.Split(new char[] {' '}, 
    StringSplitOptions.RemoveEmptyEntries).Length;
}

MSDN提供这个例子,应该给你一个准确的字数统计更快的大型文件。

MSDN provides this example, should give you an accurate word count much faster on large files.

这篇关于什么是最有效的方法来计算所有的话在一个RichTextBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆