您的位置:首页 > 编程语言 > C#

C# 实现统计字符串中不同单词的出现次数【百度笔试题】

2011-12-30 13:38 681 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AlgorithmDemo
{
/*一个文本文件里面记录了很多内容,主要由各种字符组成,如字母、数字、中文、各种标点符号等。
* 请编写程序分析这个文本文件里的字符串中不同单词的出现次数。
* 单词的定义,满足其中一条的就算一个单词:
* a.纯数字组成的(如:123)
* b.纯字母组成的(如:abdsd)
* c.小数形式的(如:123.456)
* d.中文,一个中文算一个单词
* */
public class 单词统计
{
public Dictionary<string, int>[] StatItemCount(string strs)
{
//存放结果数组 0其它符号,1字母,2数字,3汉字,
Dictionary<string, int>[] value = new Dictionary<string, int>[4] {
new Dictionary<string, int> { }
, new Dictionary<string, int> { }
, new Dictionary<string, int> { }
, new Dictionary<string, int> { } };

StringBuilder tStr = new StringBuilder();
char tChar;
int perType = 0;//前一此字符类型 取值与结果数组对应 0其它符号,1字母,2数字,3汉字,
for (int i = 0; i < strs.Length; i++)
{
tChar = strs[i];
if (perType == 1)//上次是字母单词
{
if (!isLetter(tChar))//如果当前字符不是字母
{
CountWords(value[perType], tStr);
tStr.Clear();
}
}
else if (perType == 2)//上次的是数字
{
if (!isNumber(tChar))//如果当前字符不是数字
{
if (tChar == '.' && i + 1 < strs.Length && Match(strs[i + 1], numRegex))//如果是“.”,下一位如果为数字则加入
{
tStr.Append(tChar).Append(strs[i + 1]);
i = i + 1;
continue;
}
else
{
CountWords(value[perType], tStr);
tStr.Clear();
}
}
}
if (isLetter(tChar))//如果当前是字母
{
perType = 1;
tStr.Append(tChar);
}
else if (isNumber(tChar))//如果当前是数字
{
perType = 2;
tStr.Append(tChar);
}
else if (isChinese(tChar))//如果当前是汉字
{
perType = 3;
CountWords(value[3], tChar);
tStr.Clear();
}
else
{
perType = 0;
CountWords(value[0], tChar);
tStr.Clear();
}
}
return value;
}

private void CountWords(Dictionary<string, int> counts, object key)
{
if (!counts.ContainsKey(key.ToString()))
counts[key.ToString()] = 0;
counts[key.ToString()] = counts[key.ToString()] + 1;
}

string numRegex = "[0-9]";
string letterRegex = "[A-Za-z]";
string chineseRegex = "[\u4e00-\u9fa5]";

private bool isLetter(char c)
{
return Match(c, letterRegex);
}

private bool isNumber(char c)
{
return Match(c, numRegex);
}

private bool isChinese(char c)
{
return Match(c, chineseRegex);
}

private bool Match(object source, object regex)
{
return System.Text.RegularExpressions.Regex.IsMatch(source.ToString(), regex.ToString());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐