C#判断单词个数方法总结
程序员文章站
2023-12-16 11:20:40
方法一:
判断英文单词个数:
using system;
namespace findword
{
class program
{...
方法一:
判断英文单词个数:
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<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.排序使用插入排序(稳定)
public void statisticswords(string path) { if (!file.exists(path)) { console.writeline("文件不存在!"); return; } hashtable ht = new hashtable(stringcomparer.ordinalignorecase); streamreader sr = new streamreader(path, system.text.encoding.utf8); string line = sr.readline(); string[] wordarr = null; int num = 0; while (line.length > 0) { // matchcollection mc = regex.matches(line, @"\b[a-z]+", regexoptions.compiled | regexoptions.ignorecase); //foreach (match m in mc) //{ // 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 (string s in wordarr) { 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(); } arraylist keyslist = new arraylist(ht.keys); //对hashtable中的keys按字母序排列 keyslist.sort(); //按次数进行插入排序【稳定排序】,所以相同次数的单词依旧是字母序 string tmp = string.empty; int valuetmp = 0; for (int i = 1; i < keyslist.count; i++) { tmp = keyslist[i].tostring(); valuetmp = (int)ht[keyslist[i]];//次数 int j = i; while (j > 0 && valuetmp > (int)ht[keyslist[j - 1]]) { keyslist[j] = keyslist[j - 1]; j--; } keyslist[j] = tmp;//j=0 } //打印出来 foreach (object item in keyslist) { console.writeline((string)item + ":" + (string)ht[item]); } }