C#统计字符串中某字符串出现次数示例

作者:袖梨 2022-06-25

例1

 代码如下 复制代码

计算一个字符串中的某个子串出现的次数,有没有好的方法?
///


/// 计算字符串中子串出现的次数
///

/// 字符串
/// substring”>子串
/// 出现的次数
static int SubstringCount(string str, string substring)
{
if (str.Contains(substring))
{
string strReplaced = str.Replace(substring, “”);
return (str.Length – strReplaced.Length) / substring.Length;
}

return 0;
}
int count = SubstringCount(“ddddfdfhgfjghjhgjghjhjhjhjhj”, “gh”);


例2 哈希表

 

 代码如下 复制代码

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();

例3 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();

相关文章

精彩推荐