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

标签 c# generics string

我需要经常将“字符串 block ”(包含返回字符的字符串,例如来自文件或文本框)转换为 List<string> .

有什么方法比下面的 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 )

关于c# - 将由返回字符分隔的字符串转换为 List<string> 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2326229/

相关文章:

c# - Entity Framework 6 代码优先并发

java - 对于java,如何确保内部接口(interface)和外部接口(interface)具有相同的泛型?

c - 如何使用C中的指针在结构类型数组中获取字符串输入

c# - 无法理解如何决定何时使用 Hidden() 以及何时使用 HiddenFor()

c# - JWT 不会使用 Blazor 存储在 ASP.NET Core 中

c# - 如何调试作为 SSIS 项目一部分的脚本?

java - Class<?>#getTypeParameters() 的返回类型是什么?

Java 泛型 : Type mismatch: cannot convert from Integer to K

c++ - 如何从文件中提取路径?

python - 对字符串进行排序以生成新字符串