我有一个特殊的问题..!
我有一个字符串,在多个步骤中具有一些常量值.例如,考虑以下刺痛.
string tmpStr = "Hello _tmp_ how is _tmp_ this possible _tmp_ in C#...?"
现在我想用存储在数组中的值替换字符串中的每个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); }
您需要确保找到的匹配数永远不会超过数组的长度,如上所示.
编辑:响应评论,这可以很容易地使用C#2.0,用这个替换lambda:
string result = rx.Replace(input,delegate(Match m) { return array[index++]; });
原文地址:https://www.jb51.cc/csharp/243038.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。