帮写一个算法!

霜寒月冷 2008-11-17 10:39:24
richtextbox.Text里面有许多字符串,如下:
aaabbbcccaaabbbcccaaabbbcccaaacccaaaddd
现在要将之筛选出,重复出现越多的排在前面。
上面的字符串:
aaa出现了5次;
ccc出现了4次;
bbb出现了3次;
ddd出现了1次;

运行结果:
aaa
ccc
bbb
ddd
...全文
135 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
止戈而立 2008-11-17
  • 打赏
  • 举报
回复
又是正则

using System.Text.RegularExpressions;

private int GetCount(string text,string keyWord)
{
Regex reg=new Regex(keyWord);
return reg.Matchs(text).Length;
}

chinaicm 2008-11-17
  • 打赏
  • 举报
回复
我写的这个是统计连续出现的字符.单个字符也算是连续字符.
chinaicm 2008-11-17
  • 打赏
  • 举报
回复
public string[] SortString(string source)
{
Dictionary<String, int> list = new Dictionary<String, int>();
int iStart = 0;
for (int i = 0; i < source.Length; i++)
{
if (i + 1 < source.Length && source[i] != source[i + 1])
{
string key = source.Substring(iStart, i + 1 - iStart);
SetValue(list, key);
iStart = i + 1;
}
else if (i + 1 == source.Length)
{
string key = source.Substring(iStart);
SetValue(list, key);
}
}

string[] stArray = new string[list.Count];
int[] iArray = new int[list.Count];
list.Keys.CopyTo(stArray, 0);
list.Values.CopyTo(iArray, 0);
for (int i = 0; i < iArray.Length; i++)
{
string stNow = stArray[i];
for (int j = i + 1; j < iArray.Length; j++)
{
if (iArray[j] > iArray[i])
{
stArray[i] = stArray[j];
stArray[j] = stNow;
}
}
}

return stArray;
}

public void SetValue(Dictionary<String, int> dic, string key)
{
if (!dic.ContainsKey(key))
{
dic.Add(key, 1);
}
else
{
dic[key] = dic[key] + 1;
}
}
devilli 2008-11-17
  • 打赏
  • 举报
回复
觉得可以用正则
霜寒月冷 2008-11-17
  • 打赏
  • 举报
回复
up
霜寒月冷 2008-11-17
  • 打赏
  • 举报
回复
重写例子
richtextbox.Text里面有许多字符串,如下:
“aaa”,“bbb”,“ccc”,“aaa”,“bbb”,“ccc”,“aaa”,“bbb”,“ccc”,“aaa”,“ccc”,“aaa”,“ddd”
现在要将之筛选出,重复出现越多的排在前面。
上面的字符串:
aaa出现了5次;
ccc出现了4次;
bbb出现了3次;
ddd出现了1次;

运行结果:
aaa
ccc
bbb
ddd
霜寒月冷 2008-11-17
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 wonture 的回复:]
a算不算你说的字符串?a出现的次数明显比aaa多哦。你的字符串是怎样一个规则?
[/Quote]
a不算吧,我一是间举的一个例子,没考虑那么多。暂不考虑单个字符的。
实际字符要比这复杂的多!
愚痴鱼 2008-11-17
  • 打赏
  • 举报
回复
字符串的划分规则必须要先明确,同1楼
wonture 2008-11-17
  • 打赏
  • 举报
回复
a算不算你说的字符串?a出现的次数明显比aaa多哦。你的字符串是怎样一个规则?
wonture 2008-11-17
  • 打赏
  • 举报
回复
a算不算你说的字符?a出现的次数明显比aaa多哦。你的字符串是怎样一个规则?
生财 2008-11-17
  • 打赏
  • 举报
回复
.楼上各位都是高人啊.受教了.
RexZheng 2008-11-17
  • 打赏
  • 举报
回复

string text = "aaabbbcccaaabbbcccaaabbbcccaaacccaaaddd";
string pattern = @"(.)\1*";
Dictionary<string, int> dic = new Dictionary<string, int>();
Regex.Replace(text, pattern, delegate(Match m)
{
if (dic.ContainsKey(m.Value))
{
dic[m.Value]++;
}
else
{
dic.Add(m.Value, 1);
}
return null;
});

foreach (string key in dic.Keys)
{
Console.WriteLine(key + ": " + dic[key]);
}



输出:

aaa: 5
bbb: 3
ccc: 4
ddd: 1

111,125

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧