一聚教程网:一个值得你收藏的教程网站

热门教程

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

时间:2022-06-25 08:17:16 编辑:袖梨 来源:一聚教程网

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

热门栏目