Mona Coder
Mona Coder

Reputation: 6316

How to replace text with index value in 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?

Upvotes: 5

Views: 1240

Answers (4)

Amit Joki
Amit Joki

Reputation: 59232

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

Upvotes: 11

Markus Safar
Markus Safar

Reputation: 6580

/// <summary>
/// Replaces each existing key within the original string by adding a number to it.
/// </summary>
/// <param name="original">The original string.</param>
/// <param name="key">The key we are searching for.</param>
/// <param name="offset">The offset of the number we want to start with. The default value is 0.</param>
/// <param name="increment">The increment of the number.</param>
/// <returns>A new string where each key has been extended with a number string with "offset" and beeing incremented with "increment".The default value is 1.</returns>
/// <example>
/// Assuming that we have an original string of "mapmapmapmap" and the key "map" we
/// would get "map0map1map2map3" as result.
/// </example>
public static string AddNumberToKeyInString(string original, string key, int offset = 0, int increment = 1)
{
    if (original.Contains(key))
    {
        int counter = offset;
        int position = 0;
        int index;

        // While we are withing the length of the string and
        // the "key" we are searching for exists at least once
        while (position < original.Length && (index = original.Substring(position).IndexOf(key)) != -1)
        {
            // Insert the counter after the "key"
            original = original.Insert(position + key.Length, counter.ToString());
            position += index + key.Length + counter.ToString().Length;
            counter += increment;
        }
     }

     return original;
}

Upvotes: 0

nvuono
nvuono

Reputation: 3363

Something along these lines should give you an idea of what you're trying to do:

static void Main(string[] args)
    {
        string text = File.ReadAllText(@"C:\temp\map.txt");
        int mapIndex = text.IndexOf("map");
        int hitCount = 0;
        int hitTextLength = 1;
        while (mapIndex >= 0 )
        {
            text = text.Substring(0, mapIndex) + "map" + hitCount++.ToString() + text.Substring(mapIndex + 2 + hitTextLength);
            mapIndex = text.IndexOf("map", mapIndex + 3 + hitTextLength);
            hitTextLength = hitCount.ToString().Length;
        }
        File.WriteAllText(@"C:\temp\map1.txt", text);
    }

Due to the fact that strings are immutable this wouldn't be the ideal way to deal with large files (1MB+) as you would be creating and disposing the entire string for each instance of "map" in the file.

For an example file:

map hat dog
dog map cat

lost cat map

mapmapmaphat

map

You get the results:

map0 hat dog
dog map1 cat

lost cat map2

map3map4map5hat

map6

Upvotes: -1

Simon
Simon

Reputation: 2960

It's because you are replacing the same occurrence of map each time. So the resulting string will have map9876543210 map9876543210 map9876543210 for 10 iterations, if the original string was "map map map". You need to find each individual occurrence of map, and replace it. Try using the indexof method.

Upvotes: -1

Related Questions