如何检查流读行中是否有4个或更多空格

时间:2018-12-13 20:20:19

标签: c# char streamreader

我正在尝试替换文本文件中管道的空间,但是如果有4个或更多空间。到目前为止,我的代码是:

dplyr

我的想法是通过方法中的参数获取空格数,但是,我不知道如何放置line.Replace(4.space或4 char.IsWhiteSpace(),分隔符)之类的东西。希望你对我的解释很好

3 个答案:

答案 0 :(得分:1)

您可以使用RegEx来执行此操作,并且可以创建一个接受变量输入的方法(因此,您可以指定字符和要替换的连续实例的最小数量,以及替换字符串:

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

它可以这样称呼:

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

输出

enter image description here

答案 1 :(得分:1)

  

我的想法是通过方法中的参数获取空格数,但我不知道如何放置line.Replace(4.space或4 char.IsWhiteSpace(),分隔符)之类的东西

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

这样称呼它:

string MyNewFile = "...";
using (StreamWriter sWriter = new StreamWriter(MyNewFile, false, encoding, 1))
{
    foreach(string line in File.ReadLines(myFile))
    {
         sWriter.WriteLine(SpacesToDelimiter(line));
    }
}

答案 2 :(得分:0)

正则表达式是完成这项工作的好工具。试试这个:

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

这与此处的答案非常相似:How do I replace multiple spaces with a single space in C#?