查找字符串出现的位置

 protected void Page_Load(object sender, EventArgs e)
        {
            string str = "abcqqqqqabchahhabcaaabcssssdbsssabcaadcsssabc";
            string key = "abc";
            MatchCollection mc;
            Regex r = new Regex(key); // 定义一个Regex对象实例
            mc = r.Matches(str);           
            List<int> matchposition = new List<int>();
            for (int i = 0; i < mc.Count; i++) //在字符串中找到所有匹配
            {
                var s = mc[i].Value; //将匹配的字符串添在字符串数组中
                if (s == key)
                {
                    matchposition.Add(mc[i].Index); //记录匹配字符的位置
                }
            }
            for (int j = 0; j < matchposition.Count(); j++)
            {
                Response.Write(matchposition[j] + "<br />");
            }
        }

  

posted @ 2014-04-14 23:01  晓风拂月  阅读(2065)  评论(0编辑  收藏  举报