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
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