Home > database >  How to replace string with incrementing int in .NET?
How to replace string with incrementing int in .NET?

Time:12-05

If I have a string:

mystring = "<p></p><p></p><p></p>"

so basically 3 empty paragraphs

if I want the end result to be:

<p id='1'></p><p id='2'></p><p id='3'></p>

how can I do that using replace or similar function? (in c#)

CodePudding user response:

As mentioned in the comments you can use regex replace with the help of MatchEvaluator. Credits to this SO answer.

public static void Main()
    {
        string text = "<p></p><p></p><p></p>";
        Console.WriteLine(text);
        Console.WriteLine(Transform(text));
    }

    static string Transform(string text)
    {
        int matchNumber = 0;
        return Regex.Replace(text, @"<p>", m => Replacement(m.Captures[0].Value, matchNumber  ));
    }

    static string Replacement(string s, int i)
    {
        return string.Format("{0} id='{1}'>", s.Replace(">", ""), i   1);
    }

Fiddle

CodePudding user response:

public string repeat(int count)
{
    string out = "";
    for (int i = 1; i <= count; i  )
    {
        out  = $"<p id='{i}'>";
    }
    return out;
}
  • Related