Easiest way to split a string on newlines in .NET?

后端 未结 16 2319
抹茶落季
抹茶落季 2020-11-22 06:57

I need to split a string into newlines in .NET and the only way I know of to split strings is with the Split method. However that will not allow me to (easily) split on a ne

相关标签:
16条回答
  • 2020-11-22 07:37

    Very easy, actually.

    VB.NET:

    Private Function SplitOnNewLine(input as String) As String
        Return input.Split(Environment.NewLine)
    End Function
    

    C#:

    string splitOnNewLine(string input)
    {
        return input.split(environment.newline);
    }
    
    0 讨论(0)
  • 2020-11-22 07:40

    Examples here are great and helped me with a current "challenge" to split RSA-keys to be presented in a more readable way. Based on Steve Coopers solution:

        string Splitstring(string txt, int n = 120, string AddBefore = "", string AddAfterExtra = "")
        {
            //Spit each string into a n-line length list of strings
            var Lines = Enumerable.Range(0, txt.Length / n).Select(i => txt.Substring(i * n, n)).ToList();
            
            //Check if there are any characters left after split, if so add the rest
            if(txt.Length > ((txt.Length / n)*n) )
                Lines.Add(txt.Substring((txt.Length/n)*n));
    
            //Create return text, with extras
            string txtReturn = "";
            foreach (string Line in Lines)
                txtReturn += AddBefore + Line + AddAfterExtra +  Environment.NewLine;
            return txtReturn;
        }
    

    Presenting a RSA-key with 33 chars width and quotes are then simply

    Console.WriteLine(Splitstring(RSAPubKey, 33, "\"", "\""));
    

    Output:

    Hopefully someone find it usefull...

    0 讨论(0)
  • 2020-11-22 07:46

    For a string variable s:

    s.Split(new string[]{Environment.NewLine},StringSplitOptions.None)
    

    This uses your environment's definition of line endings. On Windows, line endings are CR-LF (carriage return, line feed) or in C#'s escape characters \r\n.

    This is a reliable solution, because if you recombine the lines with String.Join, this equals your original string:

    var lines = s.Split(new string[]{Environment.NewLine},StringSplitOptions.None);
    var reconstituted = String.Join(Environment.NewLine,lines);
    Debug.Assert(s==reconstituted);
    

    What not to do:

    • Use StringSplitOptions.RemoveEmptyEntries, because this will break markup such as Markdown where empty lines have syntactic purpose.
    • Split on separator new char[]{Environment.NewLine}, because on Windows this will create one empty string element for each new line.
    0 讨论(0)
  • 2020-11-22 07:46

    Silly answer: write to a temporary file so you can use the venerable File.ReadLines

    var s = "Hello\r\nWorld";
    var path = Path.GetTempFileName();
    using (var writer = new StreamWriter(path))
    {
        writer.Write(s);
    }
    var lines = File.ReadLines(path);
    
    0 讨论(0)
提交回复
热议问题