1

I'm trying to remplace space for pipes in a text file but if there are 4 or more spaces. my code till now is:

string MyNewFile;
using (StreamWriter sWriter = new StreamWriter(MyNewFile, false, encoding, 1))
{
    using (StreamReader sReplaceReader = new StreamReader(myFile))
    {
        string line, textLine = "";

        while ((line = sReplaceReader.ReadLine()) != null)
        {
            if (line.Contains("    ")>=4 )//if contains 4 or more spaces
            {
                textLine = line.Replace("    ", "|");
            }

            sWriter.WriteLine(textLine);
        }
    } 
}

My idea is to get the number of spaces by a parameter in a method but, I dont know how to put something like line.Replace(4.space or 4 char.IsWhiteSpace(), separator). I hope you have explained me well

maccettura
  • 10,514
  • 3
  • 28
  • 35
greg dorian
  • 136
  • 1
  • 3
  • 14
  • 1
    Are you looking for 4 or more *contiguous* spaces or 4 or more spaces *anywhere*? – dbc Dec 13 '18 at 20:27

3 Answers3

1

You can use RegEx to do this, and could create a method that takes variable input (so you can specify the character and the minimum number of consecutive instances to replace, along with a replacement string:

public static string ReplaceConsecutiveCharacters(string input, char search,
    int minConsecutiveCount, string replace)
{
    return input == null
        ? null
        : new Regex($"[{search}]{{{minConsecutiveCount},}}", RegexOptions.None)
            .Replace(input, replace);
}

It can then be called like:

static void Main()
{
    var testStrings = new List<string>
    {
        "Has spaces      scattered          throughout  the   body    .",
        "      starts with spaces and ends with spaces         "
    };

    foreach (var testString in testStrings)
    {
        var result = ReplaceConsecutiveCharacters(testString, ' ', 4, "|");
        Console.WriteLine($"'{testString}' => '{result}'");
    }

    GetKeyFromUser("\nDone! Press any key to exit...");
}

Output

enter image description here

Rufus L
  • 36,127
  • 5
  • 30
  • 43
1

My idea is to get the number of spaces by a parameter in a method but, I dont know how to put something like line.Replace(4.space or 4 char.IsWhiteSpace(), separator)

private string SpacesToDelimiter(string input, int numSpaces  = 4, string delimiter = "|")
{
    string target = new String(' ', numSpaces);
    return input.Replace(target, delimiter);
}

Call it like this:

string MyNewFile = "...";
using (StreamWriter sWriter = new StreamWriter(MyNewFile, false, encoding, 1))
{
    foreach(string line in File.ReadLines(myFile))
    {
         sWriter.WriteLine(SpacesToDelimiter(line));
    }
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
0

Regex is a good tool for the job. Try this:

string MyNewFile;
using (StreamWriter sWriter = new StreamWriter(MyNewFile, false, encoding, 1))
{
    using (StreamReader sReplaceReader = new StreamReader(myFile))
    {
        string line, textLine = "";

        while ((line = sReplaceReader.ReadLine()) != null)
        {
            RegexOptions options = RegexOptions.None;
            Regex regex = new Regex("[ ]{4,}", options);     
            string textLine = regex.Replace(line, "|");

            sWriter.WriteLine(textLine);
        }
    } 
}

It's a very similar solution to the answer here: How do I replace multiple spaces with a single space in C#?

Sam W
  • 599
  • 2
  • 16