将由返回字符分隔的字符串转换为List< string>的最佳方法是什么? [英] What is the best way to convert a string separated by return chars into a List<string>?
本文介绍了将由返回字符分隔的字符串转换为List< string>的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
List< string> / code> 。
p>
using System;
使用System.Collections.Generic;
使用System.Linq;
命名空间TestConvert9922
{
class程序
{
static void Main(string [] args)
{
string testBlock =line one+ Environment.NewLine +
line two+ Environment.NewLine +
line three+ Environment.NewLine +
line four+ Environment.NewLine +
第五行;
列表< string> lines = StringHelpers.ConvertBlockToLines(testBlock);
lines.ForEach(l => Console.WriteLine(l));
Console.ReadLine();
}
}
public static class StringHelpers
{
public static List< string> ConvertBlockToLines(这个字符串块)
{
字符串fixedBlock = block.Replace(Environment.NewLine,§);
列表< string> lines = fixedBlock.Split('§')。ToList< string>();
lines.ForEach(s => s = s.Trim());
回报行;
}
}
}
解决方案
列表< string> newStr = str.Split(new [] {Environment.NewLine},StringSplitOptions.None).ToList();
这会将连续换行符保留为空字符串(请参见 StringSplitOptions )
I need to often convert a "string block" (a string containing return characters, e.g. from a file or a TextBox) into List<string>
.
What is a more elegant way of doing it than the ConvertBlockToLines method below?
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();
This will keep consecutive newlines as empty strings (see StringSplitOptions)
这篇关于将由返回字符分隔的字符串转换为List< string>的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文