SoFunction
Updated on 2025-03-07

Summary of C# Methods for judging word count

Method 1:

Determine the number of English words:

using System;

namespace FindWord
{
  class Program
  {
    static void Main(string[] args)
    {
      string space = " ";
      string str = "hello world" + space;
      int count = 0;
      bool start = false;
      for (int i=0;i<;i++)
      {
        if (Char .IsLetter(str[i]))
        {
          start = true;
        }
        if (!(str[i])&&start)
        {
          count++;
          start = false;
        }
        
      }
      (count);
      ();
    }
  }
}

Method 2:

The idea of ​​C# statistics on the number of words in English strings is as follows:

1. Use Hashtable (efficient) set to record the number of occurrences of each word

2. Use ArrayList to arrange the keys in Hashtable in alphabetical order

3. Sort using insert sort (stable)

public void StatisticsWords(string path) {
if (!(path))
{
("The file does not exist!");
return;
}
Hashtable ht = new Hashtable();
StreamReader sr = new StreamReader(path, .UTF8);
string line = ();
string[] wordArr = null;
int num = 0;
while ( &gt; 0)
{
//  MatchCollection mc = (line, @"\b[a-z]+",  | );
//foreach (Match m in mc)
//{
//  if (())
//  {
//    num = Convert.ToInt32(ht[]) + 1;
//    ht[] = num;
//  }
//  else
//  {
//    (, 1);
//  }
//}
//line = ();
wordArr = (' ');
foreach (string s in wordArr)
{
if ( == 0)
continue;
//Remove punctuation pointsline = (line, @"[\p{P}*]", "", );
//Add words to have a hash tableif ((s))
{
num = Convert.ToInt32(ht[s]) + 1;
ht[s] = num;
}
else
{
(s, 1);
}
}
line = ();
}
ArrayList keysList = new ArrayList();
//Order the keys in Hashtable in alphabetical order();
//Insert sort by number of times [Stable sort], so words with the same number of times are still alphabeticalstring tmp = ;
int valueTmp = 0;
for (int i = 1; i &lt; ; i++)
{
tmp = keysList[i].ToString();
valueTmp = (int)ht[keysList[i]];//frequencyint j = i;
while (j &gt; 0 &amp;&amp; valueTmp &gt; (int)ht[keysList[j - 1]])
{
keysList[j] = keysList[j - 1];
j--;
}
keysList[j] = tmp;//j=0
}
//Print it outforeach (object item in keysList)
{
((string)item + ":" + (string)ht[item]);
}
}