c# 如何判断字符串中相同字符串的个数 (相同字符在字符串中出现的次数)
/// <summary> /// 计算字符串中子串出现的次数 /// </summary> /// <param name="str">字符串</param> /// <param name="substring">子串</param> /// <returns>出现的次数</returns> 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; }
调用
string a = "abcdefababctrb"; string b = "b"; int c = SubstringCount(a, b); //这里的c就是b在a中出现的次数了 Console.Write(c); Console.ReadLine();