我需要经常将“字符串 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/