【问题标题】:How to count the number of words? [duplicate]如何计算字数? [复制]
【发布时间】:2015-01-21 18:05:28
【问题描述】:

我能够计算文本框中的字符数。但我不知道如何计算字数并将它们打印到标签。

【问题讨论】:

  • 你一定在找this link
  • 我的意思是我有一个文本框“我的名字是卢卡斯”我写了我标记了 4 个字
  • @lukaszskrzypczak:多少字:my name is:lukas,my sister is hannah.
  • 请解释!你还想要什么。由于给定链接中存在字数统计机制
  • 每个单词后面必须跟一个空格,这是一个语法规则,因此在您的示例中,单词是 5。

标签: c# textbox count label


【解决方案1】:

假设你用空格来区分每个单词,试试这个:-

int count = YourtextBoxId.Text
                         .Split(new char[] {' '},StringSplitOptions.RemoveEmptyEntries)
                         .Count();

好的,正如@Tim Schmelter 所建议的那样,如果除了空格之外您还有不同的分隔符knids,您可以扩展它:-

int count = YourtextBoxId.Text
               .Split(new char[] {' ','.',':'},StringSplitOptions.RemoveEmptyEntries)
               .Count();

【讨论】:

  • 一个空格作为分隔符不够用:my name is:lukas,my sister is hannah 6 个字?但是,您可以轻松扩展Split 的列表:.Split(new char[] {' ', ':', '.'}
  • 如果一个文本包含一百万个空格,你将在内存中获得一百万个字符串。 GC喜欢你:)
  • @TimSchmelter - 谢谢,已更新答案。
  • @ViacheslavSmityukh - Textbox 文本包含数百万个空格?听起来不切实际。
  • 文本编辑器应用的多行文本框可以
【解决方案2】:

第一点是在实现代码之前你应该知道的“WORD”的定义。

所以如果WORD定义为一个字母序列,可以用下面的代码来计算字数:

public int WordsCount(string text)
{
    if (string.IsNullOrEmpty(text))
    {
        return 0;
    }

    var count = 0;
    var word = false;

    foreach (char symbol in text)
    {
        if (!char.IsLetter(symbol))
        {
            word = false;
            continue;
        }

        if (word)
        {
            continue;
        }

        count++;
        word = true;
    }

    return count;
}

【讨论】:

  • +1 Char.IsLetter 不包括.,:- 等标点符号,所以这是一个好主意,也不需要创建临时String.Split 之类的字符串。一个小的改进:使用string.IsNullOrWhiteSpace 而不是string.IsNullOrEmpty
  • 你说得对,使用 IsNullOrWhiteSpace 是个好主意。但它会降低从大量空格开始并以单个单词结尾的源的性能。
  • 那是过早的优化和非常罕见的极端情况。
  • @TimSchmelter 我完全同意你的看法
【解决方案3】:

你可以像下面的例子一样使用Regex.Matches()

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
    const string t1 = "To be or not to be, that is the question.";
    Console.WriteLine(WordCounting.CountWords1(t1));
    Console.WriteLine(WordCounting.CountWords2(t1));

    const string t2 = "Mary had a little lamb.";
    Console.WriteLine(WordCounting.CountWords1(t2));
    Console.WriteLine(WordCounting.CountWords2(t2));
    }
}

/// <summary>
/// Contains methods for counting words.
/// </summary>
public static class WordCounting
{
    /// <summary>
    /// Count words with Regex.
    /// </summary>
    public static int CountWords1(string s)
    {
    MatchCollection collection = Regex.Matches(s, @"[\S]+");
    return collection.Count;
    }

    /// <summary>
    /// Count word with loop and character tests.
    /// </summary>
    public static int CountWords2(string s)
    {
    int c = 0;
    for (int i = 1; i < s.Length; i++)
    {
        if (char.IsWhiteSpace(s[i - 1]) == true)
        {
        if (char.IsLetterOrDigit(s[i]) == true ||
            char.IsPunctuation(s[i]))
        {
            c++;
        }
        }
    }
    if (s.Length > 2)
    {
        c++;
    }
    return c;
    }
}

【讨论】:

    【解决方案4】:

    您可以尝试使用空格分割文本框中的字符串。

    string[] words = textbox.Text.Split(' '); // <-- Space character
    int numberOfWords = words.Length;
    label.Text = "Number of words are: " + numberOfWords;
    

    【讨论】:

      【解决方案5】:
      MyTextbox.Text.Split(' ').Count()
      

      【讨论】:

        【解决方案6】:

        这对我有用..

        var noOfWords = Regex.Replace(textBox1.Text, "[^a-zA-Z0-9_]+", " ")
                        .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                        .Length;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-05-19
          • 2011-12-04
          • 1970-01-01
          • 2013-01-17
          • 2012-11-30
          • 1970-01-01
          • 2017-02-23
          • 1970-01-01
          相关资源
          最近更新 更多