简体   繁体   English

将返回字符分隔的字符串转换为List <string>的最佳方法是什么?

[英]What is the best way to convert a string separated by return chars into a List<string>?

I need to often convert a "string block" (a string containing return characters, eg from a file or a TextBox) into List<string> . 我需要经常将“字符串块” (包含返回字符的字符串,例如从文件或TextBox) 转换为List<string>

What is a more elegant way of doing it than the ConvertBlockToLines method below? 比下面的ConvertBlockToLines方法更优雅的方法是什么?

using System;
using System.Collections.Generic;
using System.Linq;

namespace TestConvert9922
{
    class Program
    {
        static void Main(string[] args)
        {
            string testBlock = "line one" + Environment.NewLine +
                "line two" + Environment.NewLine +
                "line three" + Environment.NewLine +
                "line four" + Environment.NewLine +
                "line five";

            List<string> lines = StringHelpers.ConvertBlockToLines(testBlock);

            lines.ForEach(l => Console.WriteLine(l));
            Console.ReadLine();
        }
    }

    public static class StringHelpers
    {
        public static List<string> ConvertBlockToLines(this string block)
        {
            string fixedBlock = block.Replace(Environment.NewLine, "§");
            List<string> lines = fixedBlock.Split('§').ToList<string>();
            lines.ForEach(s => s = s.Trim());
            return lines;
        }

    }
}
List<string> newStr = str.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();

这会将连续的换行符保留为空字符串(请参阅StringSplitOptions

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());

Have you tried splitting on newline/carriage return and using the IEnumerable ToList extension? 您是否尝试拆分换行/回车并使用IEnumerable ToList扩展?

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();

Hmm. 嗯。 You know that string now has a .Split() that takes a string[] array, right? 你知道string现在有一个.Split(),它接受一个string[]数组,对吗?

So ... 所以......

string[] lines = data.Split(
    new string[1]{ Environment.NewLine },
    StringSplitOptions.None
);

ou can use RegEx.Split to split directly using the Enviroment.NewLine. 您可以使用RegEx.Split直接使用Enviroment.NewLine进行拆分。

public static List<string> ConvertBlockToLines(this string block)
{
   return Regex.Split(block, Environment.NewLine).ToList();
}

LINQ! LINQ!

var linesEnum = testBlock.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).AsEnumerable();

List<string> lines = linesEnum.ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM