0

I have a string like this:

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

And an array like this:

var valArray = new[] { "Val0", "Val1", "Val2", "Val3" };

I want to replace "{index}" substring with appropriate values from array.

I've already written the code, but it looks ugly

var valArray = new[] { "Val0", "Val1", "Val2", "Val3" };
var source = "hello{1}from{2}my{3}world";
var substr = source;
string pattern = $"{Regex.Escape(start)}{".+?"}{Regex.Escape(end)}";

foreach (Match m in Regex.Matches(source, pattern))
{
    var value = m.Groups[0].Value;
    var ind = Convert.ToInt32(m.Groups[0].Value.TrimStart(start.ToCharArray()).TrimEnd(end.ToCharArray()));
    substr = substr.Replace(value, valArray[ind]);
}
return substr;

Any tips how to get this solved?

Thanks!

2
  • Result string must be like this: "helloVal1fromVal2myVal3world" Commented Mar 19, 2016 at 14:44
  • if you source will be hello{2}from{1}my{3}world and var valArray = new[] { "Val0", "Val1", "Val2", "Val3" }; what should be the output? Commented Mar 19, 2016 at 14:52

3 Answers 3

3

I think you're looking for String.Format:

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

Just keep in mind that it's indexing from 0, not from 1.

Sign up to request clarification or add additional context in comments.

6 Comments

No code must automatic find and adjust all indexes {valArray} to valArray[index]
Add valArray.Cast<object>().ToArray(), valArray will be treated as an obejct, not as array of objects to be passed as params.
@IvanGritsenko that isn't true string.Format("hello{1}from{2}my{3}world", valArray); gives helloVal1fromVal2myVal3world just fine
@weston Yep, you're right. I just looked at Ivan's comment and thought "yeah, that makes sense". Now I properly tested it - an array of strings works just fine.
@weston, Surprisely it is not working on int[] or any other struct array.
|
0

Use 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)]);

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.