有这样一个功能需求,有一个字符串,例如:“这是要处理的字符串这是要处理的字符串这是要处理的字符串”,在这个字符串中“这是”共出现了3次,如何只把第一个“这是”替换成“那是”,其它内容不变。
如何用C#实现呢?求帮助!

解决方案 »

  1.   

    bool isReplaced = false;
    string s = "这是要处理的字符串这是要处理的字符串这是要处理的字符串";
    s = Regex.Replace(s, "这是", new MatchEvaluator(m => {
        if (isReplaced) return m.Value;
        isReplace = true;
        return "那是";
    }));
      

  2.   


    string str="这是要处理的字符串这是要处理的字符串这是要处理的字符串”;
    int index = str.IndexOf("这是");
    str=str.Remove(index,2).Insert(index,"那是"));
      

  3.   

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;namespace StringReplace
    {
        class Program
        {
            static void Main(string[] args)
            {
                string txt = "这是要处理的字符串这是要处理的字符串这是要处理的字符串";
                //声明一个词语
                string str = "这是";
                int  index = txt.IndexOf(str);
                int indexLast = txt.LastIndexOf(str);
                while (true)
                {                txt=txt.Remove(index,2).Insert(index,"那是");
                    index = txt.IndexOf(str);                if (index==indexLast)
                    {
                        break;
                    }
                }
                txt = txt.Remove(index, 2).Insert(index, "那是");
                index = txt.IndexOf(str);
                Console.WriteLine(txt);
                Console.ReadKey();        }
        }
    }