现在
string str="asdfAAAasldjAAAflaAAAsjd\nasdAAAfkjAAAhsdf"string str2="BBB"我现在要用str2替换首个AAA结果"asdBBBasldjAAAflaAAAsjd\nasdAAAfkjAAAhsdf"

解决方案 »

  1.   

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;namespace ConsoleApplication9
    {
        class Program
        {
            static void Main(string[] args)
            {
                string str="asdfAAAasldjAAAflaAAAsjd\nasdAAAfkjAAAhsdf";
                string str2="BBB";
                string newstr = str.Substring(0, str.IndexOf("AAA") + 3).Replace("AAA", str2);
                Console.WriteLine(newstr + str.Substring(str.IndexOf("AAA") + 3));
            }
        }
    }
      

  2.   

    采用先移除后插入的办法:
    string str = "asdfAAAasldjAAAflaAAAsjd\nasdAAAfkjAAAhsdf";
    string str2 = "BBB";
    int index = str.IndexOf("AAA");
    string result = str.Remove(index, "AAA".Length);
    result = result.Insert(index, str2);
    Response.Write(result);
      

  3.   

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;namespace ConsoleApplication9
    {
        class Program
        {
            static void Main(string[] args)
            {
                string str="asdfAAAasldjAAAflaAAAsjd\nasdAAAfkjAAAhsdf";
                string str2="BBB";
                Regex rgx = new Regex(@"AAA");
                Console.WriteLine(rgx.Replace(str, str2,1));
            }
        }
    }
      

  4.   

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;namespace ConsoleApplication9
    {
        class Program
        {
            static void Main(string[] args)
            {
                string str="asdfAAAasldjAAAflaAAAsjd\nasdAAAfkjAAAhsdf";
                string str2="BBB";
                Regex rgx = new Regex(@"AAA");
                Console.WriteLine(rgx.Replace(str, str2,1));
                /*
                 * 输出结果:
                 * asdfBBBasldjAAAflaAAAsjd
                 * asdAAAfkjAAAhsdf
                 */
            }
        }
    }
    测试通过完全没有问题啊。。
      

  5.   


    //正则当然也是可以实现的
    void Main()
    {
    string str="asdfAAAasldjAAAflaAAAsjd\nasdAAAfkjAAAhsdf";string str2="BBB";
         Regex reg=new Regex("AAA");
        str=reg.Replace(str,str2,1);
    Console.WriteLine(str);
     /*
     asdfBBBasldjAAAflaAAAsjd
    asdAAAfkjAAAhsdf
     */
    }