Seth
Seth

Reputation: 984

Replace string on loop

I'm working on a razor page where I need to drop a series of custom fields from a variable-attribute tables. My purpose is to replace a specific pairing of symbols ('{}') with an htmlstring. To simplify however lets say i wanted to replace it with an incremental number.

This is pseudo-code for what i'm looking for.

string s = "This sample will count: {}, {}, {}."
int i = 0;
while(*string not finished*)//?
{ 
   i ++;
   s.Replace("{}", i);  
}

Output:

"This sample will count 1, 2, 3."

Is this something I need to use regex on? Any other thoughts?

EDIT

I should clarify: I am not aware of how many '{}'s until run time. The numbers may be throwing people off, I'm liking going to do something more akin to:

 s.replace("{}", stringArray[i]);

Upvotes: 0

Views: 612

Answers (4)

RJ Lohan
RJ Lohan

Reputation: 6527

A simple sample using Split to tokenise your input string;

string s = "This sample will count: {}, {}, {}.";
string[] tokens = s.Split(new[] { "{}"}, StringSplitOptions.None);
StringBuilder sb = new StringBuilder();

int counter = 1;
for (int i = 0; i < tokens.Length; i++ )
{
    sb.Append(tokens[i]);
    if (i < tokens.Length - 1)
        sb.Append(counter++);
}

Console.WriteLine(sb.ToString());

Solves your posted example, but I imagine your real requirement is going to be subtly more complicated.

Upvotes: 3

p.s.w.g
p.s.w.g

Reputation: 148980

You could do this with plain old string manupulation:

string s = "This sample will count: {}, {}, {}.";
string[] stringArray = new[] { "1", "2", "3" };
int i = 0, c = s.IndexOf("{}");
while(c >= 0)
{
    s = s.Remove(c) + stringArray[i++] + s.Substring(c + 2);  
    c = s.IndexOf("{}");
}
// s == "This sample will count: 1, 2, 3."

Or using regular expressions:

string s = "This sample will count: {}, {}, {}.";
string[] stringArray = new[] { "1", "2", "3" };
int i = 0;
s = Regex.Replace(s, "{}", m => stringArray[i++]);
// s == "This sample will count: 1, 2, 3."

Or using Linq:

string s = "This sample will count: {}, {}, {}.";
string[] stringArray = new[] { "1", "2", "3" };
s = String.Join("", s.Split(new[]{ "{}" }, StringSplitOptions.None)
                     .Select((x, i) => i < stringArray.Length ? x + stringArray[i] : x));
// s == "This sample will count: 1, 2, 3."

Upvotes: 0

Wagner DosAnjos
Wagner DosAnjos

Reputation: 6374

You can use a regular expression match evaluator as follows:

var re = new Regex(@"\{\}");

string s = "This sample will count: {}, {}, {}.";

string[] replacementStrings = new string[]{"r1", "r2", "r3"};

int i = 0;

string n = re.Replace(s, m => 
    {
        return replacementStrings[i++];
    }); 

Console.WriteLine(n); // outputs: This sample will count: r1, r2, r3.

Upvotes: 2

Haney
Haney

Reputation: 34762

If performance is important to you, traverse the string manually and write its contents to a StringBuilder (to prevent tons of string instance creations while concatenating and replacing strings) and then find and replace instances of the {}. string.IndexOf would be good to use for this. Once you're done, cache the result and output the string builder via StringBuilder.ToString()

Upvotes: 1

Related Questions