开发者

How to substitute place holders in a string with values

Given the string

string command = "%ans[1]%*100/%ans[0]%"

Will replace to %ans[1]% to array[1] %ans[0]% to array[2]

How do I substitute the place holders in command 开发者_JAVA百科with the values in the array to get the following result? Should I use Regular Expressions for this?

And using Regex.Replace ?

"test2*100/test1"


You could just use string.Format to insert your string into the command string:

string command = "{0}*100/{1}";

string[] array = new string[] { "test1", "test2" };

string.Format(command, array[1], array[0]);


You could try using a standard Replace.

Something like

string command = "%ans[1]%*100/%ans[0]%";
string[] array = new string[] { "test1", "test2" };
for (int iReplace = 0; iReplace < array.Length; iReplace++)
    command = command.Replace(String.Format("%ans[{0}]%", iReplace), array[iReplace]);


This does it, but I doubt it's what your looking for. Oh well.

for (int i = 0; i < array.Length; i++)
{
    command = command.Replace(string.Format("%ans[{0}]%", i), array[i]);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜