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

后端 未结 16 2491
抹茶落季
抹茶落季 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

    Well, actually split should do:

    //Constructing string...
    StringBuilder sb = new StringBuilder();
    sb.AppendLine("first line");
    sb.AppendLine("second line");
    sb.AppendLine("third line");
    string s = sb.ToString();
    Console.WriteLine(s);
    
    //Splitting multiline string into separate lines
    string[] splitted = s.Split(new string[] {System.Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
    
    // Output (separate lines)
    for( int i = 0; i < splitted.Count(); i++ )
    {
        Console.WriteLine("{0}: {1}", i, splitted[i]);
    }
    

提交回复
热议问题