C#判断单词个数方法总结
方法一:
判断英文单词个数:
usingSystem;
namespaceFindWord
{
classProgram
{
staticvoidMain(string[]args)
{
stringspace="";
stringstr="helloworld"+space;
intcount=0;
boolstart=false;
for(inti=0;i
方法二:
C#统计英文字符串中单词个数思路如下:
1.使用的Hashtable(高效)集合,记录每个单词出现的次数
2.采用ArrayList对Hashtable中的Keys按字母序排列
3.排序使用插入排序(稳定)
publicvoidStatisticsWords(stringpath){
if(!File.Exists(path))
{
Console.WriteLine("文件不存在!");
return;
}
Hashtableht=newHashtable(StringComparer.OrdinalIgnoreCase);
StreamReadersr=newStreamReader(path,System.Text.Encoding.UTF8);
stringline=sr.ReadLine();
string[]wordArr=null;
intnum=0;
while(line.Length>0)
{
//MatchCollectionmc=Regex.Matches(line,@"\b[a-z]+",RegexOptions.Compiled|RegexOptions.IgnoreCase);
//foreach(Matchminmc)
//{
//if(ht.ContainsKey(m.Value))
//{
//num=Convert.ToInt32(ht[m.Value])+1;
//ht[m.Value]=num;
//}
//else
//{
//ht.Add(m.Value,1);
//}
//}
//line=sr.ReadLine();
wordArr=line.Split('');
foreach(stringsinwordArr)
{
if(s.Length==0)
continue;
//去除标点
line=Regex.Replace(line,@"[\p{P}*]","",RegexOptions.Compiled);
//将单词加入哈希表
if(ht.ContainsKey(s))
{
num=Convert.ToInt32(ht[s])+1;
ht[s]=num;
}
else
{
ht.Add(s,1);
}
}
line=sr.ReadLine();
}
ArrayListkeysList=newArrayList(ht.Keys);
//对Hashtable中的Keys按字母序排列
keysList.Sort();
//按次数进行插入排序【稳定排序】,所以相同次数的单词依旧是字母序
stringtmp=String.Empty;
intvalueTmp=0;
for(inti=1;i0&&valueTmp>(int)ht[keysList[j-1]])
{
keysList[j]=keysList[j-1];
j--;
}
keysList[j]=tmp;//j=0
}
//打印出来
foreach(objectiteminkeysList)
{
Console.WriteLine((string)item+":"+(string)ht[item]);
}
}