tags:

views:

93

answers:

3

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 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"
+3  A: 

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]);
Pierre-Luc Champigny
And what if the format of `command` cannot be changed? (I don't know if this is the case; maybe @monkey_boys can clarify.)
dtb
String For mat must give fixed agument not dynamic string for used
monkey_boys
I agree with you, i only thought that's what he intended to do.
Pierre-Luc Champigny
The question of @monkey_boys was very unclear when he posted the question. After looking at another thread he posted after, @astander clearly have a better answer for him.
Pierre-Luc Champigny
+2  A: 

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]);
astander
Wow, that's kinda freaky. Well, not really I guess.
tarn
Can use Regex.Replace ?
monkey_boys
You can definitely use Regex.Replace, but it's a lot more heavy handed for such a simple problem. Regex is definitely not *needed* here. This is a simple, easy to understand, and working (or so it seems :) ) solution.
Eilon
if you can use Regex.Replace it improve in my knowleage base :)
monkey_boys
+1  A: 

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]);
}
tarn