What is the best way to convert a string separated by return chars into a List?

前端 未结 6 523
谎友^
谎友^ 2021-01-17 16:46

I need to often convert a \"string block\" (a string containing return characters, e.g. from a file or a TextBox) into List

相关标签:
6条回答
  • 2021-01-17 17:04

    ou can use RegEx.Split to split directly using the Enviroment.NewLine.

    public static List<string> ConvertBlockToLines(this string block)
    {
       return Regex.Split(block, Environment.NewLine).ToList();
    }
    
    0 讨论(0)
  • 2021-01-17 17:07

    Have you tried splitting on newline/carriage return and using the IEnumerable ToList extension?

    testBlock.Split( new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries )
             .ToList()
    

    If you want to keep empty lines but may have both linefeed and carriage return.

    textBlock.Replace( "\r\n", "\n" ).Replace( "\r", "\n" ).Split( '\n' ).ToList();
    
    0 讨论(0)
  • 2021-01-17 17:08

    Hmm. You know that string now has a .Split() that takes a string[] array, right?

    So ...

    string[] lines = data.Split(
        new string[1]{ Environment.NewLine },
        StringSplitOptions.None
    );
    
    0 讨论(0)
  • 2021-01-17 17:08

    LINQ!

    var linesEnum = testBlock.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).AsEnumerable();
    
    List<string> lines = linesEnum.ToList();
    
    0 讨论(0)
  • 2021-01-17 17:12

    No need to convert to your special sign:

    List<string> strings = str.Split(new string[] {Environment.NewLine}, StringSplitOptions.None).ToList();
    strings.ForEach(s => s = s.Trim());
    
    0 讨论(0)
  • 2021-01-17 17:28
    List<string> newStr = str.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
    

    This will keep consecutive newlines as empty strings (see StringSplitOptions)

    0 讨论(0)
提交回复
热议问题