C# 字符串中特定字符判断

/// <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 0;
        }

        /// <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 = 0;
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == customChar)
                {
                    num++;
                    if (num == nIndex)
                    {
                        return i;
                    }
                } 
            }

            return -1;
        }

// 调用例子:
// 假如有一个字符串 string str = "1,2,3,4,5,6,7,8,9"; 那么
// 1.查找','在字符串中共出现了多少次 用
SubstringCount(str,",")即可
// 2.查找','在字符串中第5次出现的下标则用
IndexOfCustomChar(str,',',5)

 

posted @ 2018-11-13 17:08  夏空  阅读(5216)  评论(0编辑  收藏  举报