C#统计字符串中字符出现的次数
方法1:自定义类
class CharNum
{
private char c;
private int num;
public char C
{
get { return c; }
}
public int Num
{
get { return num; }
set { num = value; }
}
public CharNum(char ch)
{
this.c = ch;
this.num = 1;
}
}
static void Main(string[] args)
{
/* */string s = "abbbcgg";
IList<char> alist = new List<char>();
for (int i = 0; i < s.Length; i++)
{
if (!alist.Contains(s[i]))
alist.Add(s[i]);
}
char[] c = (char[])alist.ToArray();
int length = 0;
CharNum[] data = new CharNum[c.Length];
for (int j = 0; j < s.Length; j++)
{
CharNum cn = new CharNum(s[j]);
bool plus = false;
if (length == 0)
{
data[length] = cn;
length++;
}
else
{
for (int k = 0; k < length; k++)
{
if (data[k].C == cn.C)
{
data[k].Num++;
plus = true;
break;
}
}
if (!plus)
{
data[length] = cn;
length++;
}
}
}
for (int i = 0; i < data.Length; i++)
{
Console.WriteLine("{0}:{1}",data[i].C.ToString(), data[i].Num.ToString());
}
Console.ReadKey();
}
方法2:键值集合 Dictionary<char, int>
Dictionary<char, int> dic = new Dictionary<char, int>();
String s = "aaabbs";
char[] chardata = s.ToCharArray();
foreach (char c in chardata)
{
if (!dic.ContainsKey(c))
{
dic.Add(c, 1);
}
else
{
dic[c] = dic[c] + 1;
}
}
foreach (KeyValuePair<char, int> item in dic)
{
Console.WriteLine("{0}出现{1}次", item.Key, item.Value);
}
Console.ReadLine();
方法3:哈希表
Hashtable ht = new Hashtable();
string sr = "aaabbcddddd";
char[] cr = sr.ToCharArray();
foreach (char ch in cr)
{
if (ht.ContainsKey(ch))
{
int i = (int)ht[ch];
ht.Remove(ch);
ht.Add(ch, ++i);
}
else
ht.Add(ch, 1);
}
foreach (DictionaryEntry dicEntry in ht)
{
Console.WriteLine("{0}出现{1}次", dicEntry.Key, dicEntry.Value);
}
ArrayList alist = new ArrayList(ht.Values);
alist.Sort();
object o = (object)alist[alist.Count - 1];
foreach (DictionaryEntry dicEntry in ht)
{
if (dicEntry.Value == o)
{
string str = dicEntry.Key.ToString();
Console.WriteLine("出现次数最多的字符:{0},共{1}次", str, o.ToString());
break;
}
}
Console.ReadLine();
方法4:LINQ
string s = "aaabccccef";
char[] c = s.ToCharArray();
var cc = c.GroupBy(e => e).OrderByDescending(e => e.Count()).ToList();
for (int i = 0; i < cc.Count; i++)
{
Console.WriteLine("{0}\t{1}", cc[i].Key.ToString(), cc[i].Count().ToString());
}
var ccc = c.GroupBy(e => e).OrderByDescending(e => e.Count()).First().ToList();
Console.WriteLine("{0}出现{1}次!", ccc[0].ToString(), ccc.Count().ToString());
Console.ReadKey();