用数组中的值替换子字符串

时间:2016-03-19 14:41:45

标签: c# arrays string

我有一个这样的字符串:

product

这样的数组:

'product_code' => 'required|unique:product,product_code',
'un_code' => 'required|unique:product,un_code',
'hs_code' => 'required|unique:product,hs_code',

我想替换" {index}"具有来自数组的适当值的子字符串。

我已经编写了代码,但看起来很难看

string source = hello{1}from{2}my{3}world

如何解决这个问题?

谢谢!

3 个答案:

答案 0 :(得分:3)

我认为您正在寻找String.Format

string result = string.Format(source, valArray); // "helloVal1fromVal2myVal3world"

请记住,它的索引是从0开始,而不是从1开始。

答案 1 :(得分:0)

使用Regex.Replace(string input, string pattern, MatchEvaluator evaluator)

var valArray = new[] { "Val0", "Val1", "Val2", "Val3" };
var source = "hello{1}from{2}my{3}world";

string result = Regex.Replace(
    source,
    "{(?<index>\\d+)}",
    match => valArray[int.Parse(match.Groups["index"].Value)]);

答案 2 :(得分:0)

[Test]
public void SO_36103066()
{
    string[] valArray = new[] { "Val0", "Val1", "Val2", "Val3" };
    //prefix array with another value so works from index {1}
    string[] parameters = new string[1] { null }.Concat(valArray).ToArray(); 
    string result = string.Format("hello{1}from{2}my{3}world", parameters);
    Assert.AreEqual("helloVal0fromVal1myVal2world", result);
}