/// <summary>
/// 计算字符串中子串出现的次数
/// </summary>
/// <param name="str">字符串</param>
/// <param name="substring">子串</param>
/// <returns>出现的次数</returns>
private int SubstringCount(string str, string substring)
{
if (str.Contains(substring))
{
string strReplaced = str.Replace(substring, "");
return (str.Length - strReplaced.Length) / substring.Length;
}
return ;
}
/// <summary>
/// 计算特定字符串在某字符串中出现第N次位置
/// </summary>
/// <param name="str">源字符串</param>
/// <param name="customChar">特定字符串</param>
/// <param name="nIndex">特定字符串出现的第N次</param>
/// <returns></returns>
private int IndexOfCustomChar(string str, char customChar,int nIndex)
{
int num = ;
for (int i = ; i < str.Length; i++)
{
if (str[i] == customChar)
{
num++;
if (num == nIndex)
{
return i;
}
}
}
return -;
}
// 调用例子:
// 假如有一个字符串 string str = "1,2,3,4,5,6,7,8,9"; 那么
// 1.查找','在字符串*出现了多少次 用 SubstringCount(str,",")即可
// 2.查找','在字符串中第5次出现的下标则用 IndexOfCustomChar(str,',',5)