求C#字符串拆分统计个数代码
比如:aaa,中国,人民,bbb,中国,服务,中国,aaa,ccc执行的结果出现多到少排列
结果:中国,aaa,人民,bbb,服务,ccc
(因为中国出现3,aaa出现2次,..)
程序代码:using System;
using System.Collections.Generic;
using System.Text;
namespace StringSplit
{
class Program
{
static void Main(string[] args)
{
string test = "aaa,中国,人民,bbb,中国,服务,中国,aaa,ccc";
foreach (StringTimes st in GetStringAndTimes(test))
{
Console.WriteLine(st.timers+ "," + st.value);
}
//foreach (StringTimes st in OrderByTimers(GetStringAndTimes(test)))
//{
// Console.WriteLine(st.value + "-出现次数" + st.timers.ToString() + ";");
//}
Console.WriteLine("根据出现次数排序后:");
foreach (StringTimes st in OrderByTimers(GetStringAndTimes(test)))
{
Console.Write(st.value + " ");
}
Console.ReadKey();
}
//对StringTimes进行排序
static List<StringTimes> OrderByTimers(List<StringTimes> ST)
{
List<StringTimes> st = ST;
for (int i = 0; i < st.Count; i++)
{
int currentTimes = st[i].timers;
for (int j = i; j < st.Count; j++)
{
if (st[j].timers > currentTimes)
{
StringTimes tempInt = st[i];
st[i] = st[j];
st[j] = tempInt;
currentTimes = st[j].timers;
}
else
{
continue;
}
}
}
return st;
}
static List<StringTimes> GetStringAndTimes(string Str)
{
List<StringTimes> timesAndString = new List<StringTimes>();
string[] strArray = Str.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string str in strArray)
{
bool hasShow = false;
foreach (StringTimes st in timesAndString)
{
if (str == st.value)
{
st.timers++;
hasShow = true;
break;
}
else
{
continue;
}
}
if(!hasShow)
timesAndString.Add(new StringTimes(1, str));
}
return timesAndString;
}
class StringTimes
{
public int timers;
public string value;
public StringTimes(int Timers, string Value)
{
this.timers = Timers;
this.value = Value;
}
}
}
}