Split text with '\r\n'

前端 未结 8 456
予麋鹿
予麋鹿 2020-12-28 12:42

I was following this article

And I came up with this code:

string FileName = \"C:\\\\test.txt\";

using (StreamReader sr = new StreamReader(FileNam         


        
8条回答
  •  长情又很酷
    2020-12-28 12:58

    Reading the file is easier done with the static File class:

    // First read all the text into a single string.
    string text = File.ReadAllText(FileName);
    
    // Then split the lines at "\r\n".   
    string[] stringSeparators = new string[] { "\r\n" };
    string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
    
    // Finally replace lonely '\r' and '\n' by  whitespaces in each line.
    foreach (string s in lines) {
        Console.WriteLine(s.Replace('\r', ' ').Replace('\n', ' '));
    }
    

    Note: The text might also contain vertical tabulators \v. Those are used by Microsoft Word as manual linebreaks.

    In order to catch any possible kind of breaks, you could use regex for the replacement

    Console.WriteLine(Regex.Replace(s, @"[\f\n\r\t\v]", " "));
    

提交回复
热议问题