Best way to split string into lines

前端 未结 10 797
情书的邮戳
情书的邮戳 2020-11-27 13:53

How do you split multi-line string into lines?

I know this way

var result = input.Split(\"\\n\\r\".ToCharArray(), StringSplitOptions.RemoveEmptyEntri         


        
相关标签:
10条回答
  • 2020-11-27 14:37
        private string[] GetLines(string text)
        {
    
            List<string> lines = new List<string>();
            using (MemoryStream ms = new MemoryStream())
            {
                StreamWriter sw = new StreamWriter(ms);
                sw.Write(text);
                sw.Flush();
    
                ms.Position = 0;
    
                string line;
    
                using (StreamReader sr = new StreamReader(ms))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        lines.Add(line);
                    }
                }
                sw.Close();
            }
    
    
    
            return lines.ToArray();
        }
    
    0 讨论(0)
  • 2020-11-27 14:40
    • If it looks ugly, just remove the unnecessary ToCharArray call.

    • If you want to split by either \n or \r, you've got two options:

      • Use an array literal – but this will give you empty lines for Windows-style line endings \r\n:

        var result = text.Split(new [] { '\r', '\n' });
        
      • Use a regular expression, as indicated by Bart:

        var result = Regex.Split(text, "\r\n|\r|\n");
        
    • If you want to preserve empty lines, why do you explicitly tell C# to throw them away? (StringSplitOptions parameter) – use StringSplitOptions.None instead.

    0 讨论(0)
  • 2020-11-27 14:41

    You could use Regex.Split:

    string[] tokens = Regex.Split(input, @"\r?\n|\r");
    

    Edit: added |\r to account for (older) Mac line terminators.

    0 讨论(0)
  • 2020-11-27 14:42
    string[] lines = input.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
    
    0 讨论(0)
提交回复
热议问题