gguozhenqian
            string statement = "as1{lead}1dfasdfabcdefjhij2{lead}2klmnopqrstuvwxyz3{lead}3aasdfasd4{lead}4f";


            //要求 :写出自定义的Replace方法替换第x个通配符{lead}出现的位置 
            //方法定义:Replace(string str,string pattern,string newstr,int index )

            //结果 
            //调用方法 Replace(statement,"{lead}"," first ",1)    结果"as1 first 1dfasdfabcdefjhij2{lead}2klmnopqrstuvwxyz3{lead}3aasdfasd4{lead}4f"
            //调用方法 Replace(statement,"{lead}"," third ",3)    结果"as1 first 1dfasdfabcdefjhij2{lead}2klmnopqrstuvwxyz3 third 3aasdfasd4{lead}4f"


方法一:

static string Replace(string str, string pattern, string newstr, int index)
        {
            int leadListIndex = 0;
            return Regex.Replace(str, Regex.Escape(pattern), m =>
            {
                if (++leadListIndex == index)
                    return newstr; 
                return m.Value;
            });
        }

        //精简后
        string Replace(string str, string pattern, string newstr, int index)
        {
            int leadListIndex = 0;
            return Regex.Replace(str, Regex.Escape(pattern), m => ++leadListIndex == index ? newstr : m.Value);
        }

 

方法二:

public static string GetRePlaceStr(string str, string pattern, string newstr, int index = 1)
        {
            Regex reg = new Regex(pattern);
            //查询匹配数量           
            var t = reg.Matches(str);
            return reg.Replace(str, newstr, 1, t[index - 1].Index);
        }


 

发帖求助地址:
http://bbs.csdn.net/topics/390848935?page=1#post-397896822

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-12-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-08
  • 2022-02-09
  • 2022-02-21
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-05
相关资源
相似解决方案