??
尝试1没有问题,我的这个结果是"a cb"PS.字符串经常改动时最好用StringBuildermy test:using System;
using System.Text;namespace ConsoleApplication1
{ public class ReplaceTest 
{
public static void Main() 
{ StringBuilder correctString  = new StringBuilder("a ab");
 
Console.WriteLine("The original string is:{0}'{1}'{0}", Environment.NewLine, correctString.ToString()); // Correct the spelling of "document". correctString.Replace("ab", "cb");
Console.WriteLine("After correcting the string, the result is:{0}'{1}'", 
Environment.NewLine, correctString.ToString());
Console.ReadLine();
}
}

解决方案 »

  1.   

    打错了!??
    尝试1没有问题,我的这个结果是"a c"PS.字符串经常改动时最好用StringBuildermy test:using System;
    using System.Text;namespace ConsoleApplication1
    { public class ReplaceTest 
    {
    public static void Main() 
    { StringBuilder correctString  = new StringBuilder("a ab");
     
    Console.WriteLine("The original string is:{0}'{1}'{0}", Environment.NewLine, correctString.ToString()); //Replace ab with c correctString.Replace("ab", "c");
    Console.WriteLine("After correcting the string, the result is:{0}'{1}'", 
    Environment.NewLine, correctString.ToString());
    Console.ReadLine();
    }
    }
      

  2.   

    ^_^,楼上的兄弟辛苦了。仔细读了您的方法,就您的方法而言,original string最初为"a ab",假如第一次替换想将【第一个】"a"替换成"c",但结果却输出"c cb",orginal string中的所有"a"都被替换为"c"。
      

  3.   

    原来是这个问题 :P
    最好在查找的时候就替换
    Regex类有个方法Replace()Samples:实现首字母的大写
    class RegExSample 
    {
    //将找到的匹配项的首字母大写
                      static string CapText(Match m) 
    {
    // Get the matched string.
    string x = m.ToString();
    // If the first char is lower case...
    if (char.IsLower(x[0])) 
    {
    // Capitalize it.
    return char.ToUpper(x[0]) + x.Substring(1, x.Length-1);
    }
    return x;
    }
        
    static void Main() 
    {
    string text = "four score and seven years ago";
    System.Console.WriteLine("text=[" + text + "]");

                               //第一个参数是input字符串,第二个是regex表达式
                               //第三个参数:见说明
                               string result = Regex.Replace(text, @"\w+",
    new MatchEvaluator(RegExSample.CapText));
    System.Console.WriteLine("result=[" + result + "]");
    System.Console.ReadLine();
    }
    }说明:MatchEvaluator 类型是采用单个 Match 作为输入并返回字符串的委托。其声明如下所示:public delegate String RegexMatchEvaluator(Match match);在替换过程中为每个匹配项调用一次委托。就我的理解委托的是每找到一个匹配项就执行的函数,你可以把你的替换方法写在里面
    希望对你有用