Replace all consecutive occurrences of a char with special chars

Viewed 117

I have fill in the blanks form where the length of each blank is not consistent I want to replace such banks with special code to align with business logic, below is how the formats are

It is raining ________ in the forest   
The quick _______ dog jumps over ______________ fox

I want to reformat above lines as below

It is raining [0] in the forest
The quick [0] dog jumps over [1] fox

As said the char length of each blank is not consistent, keeping that as case want to write a maintainable code in c# using either regular expression or without

EXCEPTIONS

There are some entries without any blanks in which case should return the whole passage as is

The code suggested by Tim works great my code with Tim's answer is like below. Hope may help someone

    Dictionary<string, string> dctE = new Dictionary<string, string>();
    Dictionary<string, string> dctT = new Dictionary<string, string>();
    string jsonT = string.Empty, jsonH = string.Empty;
    try
    {
        using (StreamReader r = new StreamReader(@"C:\samples\testmongo\testmongo\tamil1.txt"))
        {
            string langs = r.ReadToEnd();
            var lines = langs.Split('\n');
            for (int i = 1; i < lines.Length - 2; i += 2)
            {
                string tml = lines[i].Split(':')[1];
                    Regex regex = new Regex(@"_{2,}");
                    string[] partT = regex.Split(tml);
                    for (int j = 0; j < partT.Length; j++)
                    {
                        tml += partT[j] + "[" + j + "]";
                    }
                //dctE[lines[i].Split(':')[0].Trim()] = lines[i].Split(':')[1].Trim();
                dctT[lines[i - 1].Split(':')[0].Trim()] = tml;// lines[i].Split(':')[1].Trim();
            }

        }
        jsonT = JsonConvert.SerializeObject(dctT);

    }
    catch(Exception eX)
    {
        Console.WriteLine(eX.Message);
    }
    finally
    {
        System.IO.File.WriteAllText(@"C:\samples\testmongo\testmongo\ta_yogs.json", jsonT);
        dctE.Clear();
        dctT.Clear();
    }
1 Answers

Here is a working script. This approach is to split the input string on two or more underscores (_{2,}). Then, we iterate the string components, and join them together into a single string using a numbered for loop, using which we can figure out what the replacement placeholders should be.

string input = "The quick _______ dog jumps over ______________ fox";
Regex regex = new Regex(@"_{2,}");
string[] parts = regex.Split(input);
string output = "";
for (int i=0; i < parts.Length-1; i++)
{
    output += parts[i] + "[" + i + "]";
}
output += parts[parts.Length-1];
Console.WriteLine(input);
Console.WriteLine(output);

The quick _______ dog jumps over ______________ fox
The quick [0] dog jumps over [1] fox
Related