当前位置:编程学习 > C#/ASP.NET >>

如何在一个字符串中依次查找每一个匹配子字符串位置?

比如以字符串“acxyefdxycrtsxyf”
查找字符串为"xy"
依次返回每个xy的起始位置(0起):2, 7, 13 --------------------编程问答-------------------- 可以自己遍历查找,或者http://blog.csdn.net/bdmh/article/details/6090983里面有c#代码 --------------------编程问答-------------------- KMP算法! --------------------编程问答-------------------- 简单写了个
            String str ="acxyefdxycrtsxyf";
            String target = "xy";
            while (true)
            {
                int sta = str.IndexOf(target, startIndex);
                if (sta == -1)
                {
                    break;
                }
                lst.Add(sta);
                startIndex = sta + target.Length;
            } --------------------编程问答-------------------- using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSDN_Help
{
    class Program
    {
        static void Main(string[] args)
        {
            string res = "acxyefdxycrtsxyf";
            string des = "xy";
            char[] TempSpace=new Char[2];
            for (int i = 0; i <= res.Length - des.Length; i++)
            {
                res.CopyTo(i, TempSpace, 0, des.Length);
                if (new string(TempSpace).Equals(des))
                {
                    Console.WriteLine(i);
                }
            } 
        }
    }
}


当然如果要追求算法的效率,可以看看KMP算法。 --------------------编程问答-------------------- 对了,用IndexOf更方便些~~ --------------------编程问答--------------------             int[] list = Regex.Matches("acxyefdxycrtsxyf", "xy").OfType<Match>().Select(t => t.Index).ToArray();
--------------------编程问答-------------------- 4楼和6楼的答案让人感慨正则表达式和lambda表达式的威力!
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,