我有一个特殊的问题..!
我有一个字符串,在多个步骤中具有一些常量值.例如,考虑以下刺痛.
string tmpStr = "Hello _tmp_ how is _tmp_ this possible _tmp_ in C#...?"
Run Code Online (Sandbox Code Playgroud)
现在我想用存储在数组中的值替换字符串中的每个tmp,首先tmp保存数组[0],第二个tmp保存数组[1],依此类推......
知道如何实现这一点......?我使用C#2.0
这个怎么样:
string input = "Hello _tmp_ how is _tmp_ this possible _tmp_ in C#...?";
string[] array = { "value1", "value2", "value3" };
Regex rx = new Regex(@"\b_tmp_\b");
if (rx.Matches(input).Count <= array.Length)
{
int index = 0;
string result = rx.Replace(input, m => array[index++]);
Console.WriteLine(result);
}
Run Code Online (Sandbox Code Playgroud)
您需要确保找到的匹配项数量永远不会大于数组的长度,如上所示。
编辑:作为对评论的回应,通过将 lambda 替换为以下内容,可以轻松地与 C# 2.0 一起使用:
string result = rx.Replace(input, delegate(Match m) { return array[index++]; });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2845 次 |
| 最近记录: |