繁体   English   中英

C# 统计字符串中的单词

[英]C# Count the words in a string

如何使用基本的字符串函数和循环来做到这一点? 我想计算字符串中的单词。 我的问题是它仅在用户不使用多个空格时才有效。

这是我的代码:

        string phrase;
        int word = 1;


        Console.Write("Enter a phrase: ");
        phrase = Console.ReadLine();

        for (int i = 0; i<phrase.Length; i++)
        {
            if (name[i] == ' ')
            {
                word++;
            } 
        }
        Console.WriteLine(word);

您可以使用 Split() 和 Linq 来代替 for 循环:

var splitPhrase = phrase.Split(' ');
var wordCount = splitPhrase.Count(x=>x != "");

或使用 StringSplitOptions,根据评论:

var words = phrase.Split(' ', StringSplitOptions.RemoveEmptyEntrie);
var wordCount = words.Count();

一种方法是使用正则表达式将所有连续的空格“压缩”成一个实例。 那么工作就很简单了。

var str = "aaa bb      cccc d    e";
var regex = new Regex(@"\s+");
Console.WriteLine(regex.Replace(str, " ")?.Split(' ')?.Count());

如果你可以使用 LINQ,我建议这种方法:

    string[] source = phrase.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries);
    var matchQuery = from word in source
                     select word;
    
    int wordCount = matchQuery.Count();
    Console.WriteLine(wordCount);

首先,我们必须定义单词。 如果单词是

任何非空的字母序列

我们可以使用一个简单的正则表达式模式: \p{L}+

代码:

using System.Text.RegularExpressions;

...

int word = Regex.Matches(phrase, @"\p{L}+").Count;

编辑:如果你不想要正则表达式,你可以实现FSM - F inite State Machine:

  int word = 0; 
  bool inWord = false;

  foreach (var c in phrase) 
    if (char.IsLetter(c)) {
      if (!inWord) // we count beginnings of each word
        word += 1;

      inWord = true;
    }
    else
      inWord = false;
  

这里我们有两种状态: - inWord == true, false - 字符是否在某个单词中。 有了这些状态,我们就可以数出所有单词的开头。

我会创建一个字符串数据类型的数组。 然后我会在读取数据时使用拆分方法。 只要您看到定义的字符(字符是一个字母或字符),这就会拆分整个文本。 在您的情况下,定义的字符将是空格; 那是 ' '。 所以我的公式是这样的:

     string phrase;
     string[] seperated;    // this is where you would split the full name
     int word = 1;


        Console.Write("Enter a phrase: ");
        phrase = Console.ReadLine();
        seperated=phrase.Split(' ');

        for (int i = 0; i<seperated.Length; i++)
        {
             Console.WriteLine(seperated[i]); // this would print each word one by one
        }

一旦捕获分隔数组中的全名拆分,您就可以按照您想要的方式使用分隔名称、姓氏等。 seperated[0]= 将是第一个单词,seperated[1] 将是第二个单词...如果名称由总共 5 个单词组成,则可以通过 seperated[4] 到达最后一个单词。

您可以使用正则表达式模式: \S 匹配除空格以外的任何内容

string str = "Test words   test"    
MatchCollection collection = Regex.Matches(str, @"[\S]+");
int numberOfWords = collection.Count;

您可以通过使用以下 function 来实现这一点。它只返回编号。 给定句子中的单词。

public int totalWords(string sentence) {
            int wordCount = 0;
            for (int i = 0; i < sentence.Length - 1; i++)
            {
                if (sentence[i] == ' ' && Char.IsLetter(sentence[i + 1]) && (i > 0))
                {
                    wordCount++;
                }
            }
            wordCount++;
            return wordCount;
        }

假设您的单词由空格分隔,您只需Split字符串并获取结果数组的长度:

string[] words = phrase.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);

int numberOfWords = words.Length;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM