Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace text with index value in C#

Tags:

c#

I have a text file which contains a repeated string called "map" for more than 800 now I would like to replace them with map to map0, map1, map2, .....map800.

I tried this way but it didn't work for me:

void Main()    {
 string text = File.ReadAllText(@"T:\File1.txt");
   for (int i = 0; i < 2000; i++)
       {
         text = text.Replace("map", "map"+i);
       }
  File.WriteAllText(@"T:\File1.txt", text);
}

How can I achieve this?

like image 227
Mona Coder Avatar asked Mar 20 '14 18:03

Mona Coder


1 Answers

This should work fine:

void Main() {

    string text = File.ReadAllText(@"T:\File1.txt");
    int num = 0;

    text = (Regex.Replace(text, "map", delegate(Match m) {
        return "map" + num++;
    }));

    File.WriteAllText(@"T:\File1.txt", text);
}
like image 124
Amit Joki Avatar answered Oct 07 '22 21:10

Amit Joki