这是我整理的一个有趣的。现在,请记住这不是很有效,特别是对于简单的替换。但是,编写起来很有趣,并且适合于相当易读的使用模式。它还强调了一个鲜为人知的事实,即 String 实现了 IEnumerable。
public static class LinqToStrings
{
public static IQueryable<char> LinqReplace(this string source, int startIndex, int length, string replacement)
{
var querySource = source.AsQueryable();
return querySource.LinqReplace(startIndex, length, replacement);
}
public static IQueryable<char> LinqReplace(this IQueryable<char> source, int startIndex, int length, string replacement)
{
var querySource = source.AsQueryable();
return querySource.Take(startIndex).Concat(replacement).Concat(querySource.Skip(startIndex + length));
}
public static string AsString(this IQueryable<char> source)
{
return new string(source.ToArray());
}
}
下面是一些用法示例:
public void test()
{
var test = "test";
Console.WriteLine("Old: " + test);
Console.WriteLine("New: " + test.LinqReplace(0, 4, "SOMEPIG")
.LinqReplace(4, 0, "terrific")
.AsString());
}
输出:
旧:测试
新:SOMEterrificPIG
同样的方法的另一个版本,它不是那么慢,直接使用 Substring:
public static string ReplaceAt(this string source, int startIndex, int length, string replacement)
{
return source.Substring(0, startIndex) + replacement + source.Substring(startIndex + length);
}
还有一个很好的例子来说明为什么你应该分析你的代码,以及为什么你可能应该不在生产代码中使用我的 LinqToStrings 实现,下面是一个时序测试:
Console.WriteLine("Using LinqToStrings: " + new Stopwatch().Time(() => "test".LinqReplace(0, 4, "SOMEPIG").LinqReplace(4, 0, "terrific").AsString(), 1000));
Console.WriteLine("Using Substrings: " + new Stopwatch().Time(() => "test".ReplaceAt(0, 4, "SOMEPIG").ReplaceAt(4, 0, "terrific"), 1000));
在 1,000 次迭代中测量计时器滴答声,产生以下输出:
使用 LinqToStrings:3,818,953
使用子字符串:1,157