方法一:
判断英文单词个数:
usingSystem; namespaceFindWord { classProgram { staticvoidMain(string[]args) { stringspace=""; stringstr="helloworld"+space; intcount=0; boolstart=false; for(inti=0;i<str.Length;i++) { if(Char.IsLetter(str[i])) { start=true; } if(!Char.IsLetter(str[i])&&start) { count++; start=false; } } Console.WriteLine(count); Console.ReadLine(); } } }
方法二:
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;i<keysList.Count;i++) { tmp=keysList[i].ToString(); valueTmp=(int)ht[keysList[i]];//次数 intj=i; while(j>0&&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]); } }
您可能感兴趣的文章:C#统计字符串中数字个数的方法C#实现获取枚举中元素个数的方法C#统计字符串里中文汉字个数的方法c#n个数排序实现代码
C#无边框窗体实现以及拖动代码
详解C#中一维数组的插入
上述就是C#学习教程:C#判断单词个数方法总结分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/908162.html