一个文本(textstr)有多处需要替换,比如:“上海”替换为“上海市”;“北京”替换为“北京市”;“南京”替换为“南京市”我现在的做法是执行三次:
textstr.replace("上海","上海市")
textstr.replace("北京","北京市")
textstr.replace("南京","南京市")有没有更好的办法,一次替换,这样三次替换好像效率不好

解决方案 »

  1.   

    try to use regular expressionsstring s = "..........";
    s = Regex.Replace(s, "(上海|北京|南京)","$1市");
      

  2.   

    老大的方法不错!
    另外要隐入using System.Text.RegularExpressions;
      

  3.   

    trys = Regex.Replace(s, "(上海|北京|南京)(?!市)","$1市");
      

  4.   

    要转换的字符串多么?少的话,这么做using System.Text.RegularExpressions;class RegExSample 
    {   static Hashtable ht;   static string ReplaceText(Match m) 
       {
          if (ht.Contains(m.Value))
    return ht[m.Value].ToString();      return m.Value;
       }
        
       static void Main() 
       {
         ht = new Hashtable();     ht.Add("上海","上海市");
         ht.Add("职务","高级白领");
         ht.Add("新闻","最新情报");     string s= "...........";
          
         string result = Regex.Replace(s, @"上海|职务|新闻",
             new MatchEvaluator(ReplaceText));     System.Console.WriteLine("result=[" + result + "]");   }
    }
    多的话,就用你原来的方法吧
      

  5.   

    回复人: saucer(思归) 
    转换的字符多,是不是可以把这些字符分个装进变量里来替换?
    谢谢
      

  6.   

    CSDN这是怎么了,我一按结贴ie就报错关闭