首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >建议实现String.Replace(string oldValue,Func<string> newValue)函数

建议实现String.Replace(string oldValue,Func<string> newValue)函数
EN

Stack Overflow用户
提问于 2011-10-25 17:17:10
回答 3查看 1K关注 0票数 3

对于此任务,最优雅的解决方案是什么:

有一个模板字符串,例如:"<CustomAction Id=<newGuid> /><CustomAction Id=<newGuid> />"和我需要用不同的Guids替换<newGuid>

概括问题:

.Net string类有一个带有两个参数的Replace方法:字符或字符串类型的oldValue和newValue。问题是newValue是静态字符串(不是返回字符串的函数)。

下面是我的简单实现:

代码语言:javascript
复制
public static string Replace(this string str, string oldValue, Func<String> newValueFunc)
    {      
      var arr = str.Split(new[] { oldValue }, StringSplitOptions.RemoveEmptyEntries);
      var expectedSize = str.Length - (20 - oldValue.Length)*(arr.Length - 1);
      var sb = new StringBuilder(expectedSize > 0 ? expectedSize : 1);
      for (var i = 0; i < arr.Length; i++)
      {
        if (i != 0)
          sb.Append(newValueFunc());
        sb.Append(arr[i]);
      }
      return sb.ToString();
    }

你能推荐更优雅的解决方案吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-10-25 20:12:16

我认为是时候总结一下了,以避免错误的答案。

最优雅的解决方案是由leppieHenk Holterman提出的

代码语言:javascript
复制
public static string Replace(this string str, string oldValue, Func<string> newValueFunc)
{
  return Regex.Replace( str,
                        Regex.Escape(oldValue),
                        match => newValueFunc() );
} 
票数 1
EN

Stack Overflow用户

发布于 2011-10-25 19:44:56

这对我来说很有效:

代码语言:javascript
复制
public static string Replace(this string str, string oldValue,
    Func<String> newValueFunc)
{      
    var arr = str.Split(new[] { oldValue }, StringSplitOptions.None);
    var head = arr.Take(1);
    var tail =
        from t1 in arr.Skip(1)
        from t2 in new [] { newValueFunc(), t1 }
        select t2;
    return String.Join("", head.Concat(tail));
}

如果我从这个开始:

代码语言:javascript
复制
int count = 0;
Func<string> f = () => (count++).ToString();
Console.WriteLine("apple pie is slappingly perfect!".Replace("p", f));

然后我得到这样的结果:

代码语言:javascript
复制
a01le 2ie is sla34ingly 5erfect!
票数 0
EN

Stack Overflow用户

发布于 2011-10-25 20:14:26

使用

Regex.Replace(String,MatchEvaluator)

代码语言:javascript
复制
using System;
using System.Text.RegularExpressions;

class Sample {
//  delegate string MatchEvaluator (Match match);
    static public void Main(){

        string str = "<CustomAction Id=<newGuid> /><CustomAction Id=<newGuid> />";
        MatchEvaluator myEvaluator = new MatchEvaluator(m => newValueFunc());
        Regex regex = new Regex("newGuid");//OldValue
        string newStr = regex.Replace(str, myEvaluator);
        Console.WriteLine(newStr);
    }
    public static string newValueFunc(){
        return "NewGuid";
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7887117

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档