1

C# で TextFieldParser クラスを使用して読んでいるテキスト ファイルがあります。このファイルには、Notepad++ を使用して確認できる改行文字として CRLF が含まれています。このファイルのいくつかの行には、改行文字として LF が含まれています。

これらの改行文字間の最大出現回数を取得し、使用頻度の低いものを空白に置き換えて、ファイルに同じ改行文字が含まれるようにする必要があります。

これまでの私のコードは次のとおりです。

if (File.Exists(path))
{
    List<string> delimiters = new List<string> { ";", "-", ",", "|" };
    List<string> linebreakchars = new List<string> { "\r", "\r\n", "\n"};
    Dictionary<string, int> counts = delimiters.ToDictionary(key => key, value => 0);
    Dictionary<string, int> countNewLineChars = linebreakchars.ToDictionary(key => key, value => 0);
    int counter = 0;
    int counterLine = 0;
    string line;
    // Read the file and display it line by line.
    System.IO.StreamReader file =
        new System.IO.StreamReader(path);
    while ((line = file.ReadLine()) != null)
    {
        foreach (string c in delimiters)
            counts[c] = line.Count(t => t == Convert.ToChar(c));
        counter++;
        foreach(string ln in linebreakchars)
            countNewLineChars[ln] = line.Count(t => t.ToString() == ln);
        counterLine++;
    }
    var delimiter = counts.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
    var newLineChar = countNewLineChars.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
    string text = File.ReadAllText(path);
    file.Close();
    switch (newLineChar)
    {
        case "\r":
            text = Regex.Replace(text, @"(?<!\r)\n+", "");
            break;
        case "\r\n":
            text = Regex.Replace(text, @"(?<!\r)\n+", "");
            break;
        case "\n":
            text = Regex.Replace(text, @"(?<!\n)\r\n+", "");
            break;
    }
    File.WriteAllText(path, text);
}

改行文字の出現はカウントされません。

ファイルのすべての改行文字の数を取得するにはどうすればよいですか?

4

0 に答える 0