C# 如何从添加 '\n\r' 作为行尾的多行 TextBox 将字符串拆分为 List<string>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1723253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split a string into a List<string> from a multi-line TextBox that adds '\n\r' as line endings?
提问by Edward Tanguay
I've got a textbox in my XAML file:
我的 XAML 文件中有一个文本框:
<TextBox
VerticalScrollBarVisibility="Visible"
AcceptsReturn="True"
Width="400"
Height="100"
Margin="0 0 0 10"
Text="{Binding ItemTypeDefinitionScript}"
HorizontalAlignment="Left"/>
with which I get a string that I send to CreateTable(string)
which in turn calls CreateTable(List<string>)
.
用它我得到一个字符串,我发送给CreateTable(string)
它依次调用CreateTable(List<string>)
.
public override void CreateTable(string itemTypeDefinitionScript)
{
CreateTable(itemTypeDefinitionScript.Split(Environment.NewLine.ToCharArray()).ToList<string>());
}
public override void CreateTable(List<string> itemTypeDefinitionArray)
{
Console.WriteLine("test: " + String.Join("|", itemTypeDefinitionArray.ToArray()));
}
The problem is that the string obviously has '\n\r' at the end of every line so Split('\n') only gets one of them as does Split('\r'), and using Environment.Newline.ToCharArray() when I type in this:
问题是字符串显然在每一行的末尾都有 '\n\r' 所以 Split('\n') 只像 Split('\r') 一样得到其中一个,并使用 Environment.Newline.ToCharArray () 当我输入:
one
two
three
produces this:
产生这个:
one||two||three
but I want it of course to produce this:
但我当然希望它产生这个:
one|two|three
What is a one-liner to simply parse a string with '\n\r
' endings into a List<string>
?
什么是简单地将带有 ' \n\r
' 结尾的字符串解析为 a 的单行List<string>
?
采纳答案by Fredrik M?rk
Something like this could work:
像这样的事情可以工作:
string input = "line 1\r\nline 2\r\n";
List<string> list = new List<string>(
input.Split(new string[] { "\r\n" },
StringSplitOptions.RemoveEmptyEntries));
Replace "\r\n"
with a separator string suitable to your needs.
替换"\r\n"
为适合您需要的分隔符字符串。
回答by bruno conde
Use the overload of string.Split
that takes a string[]
as separators:
使用string.Split
astring[]
作为分隔符的重载:
itemTypeDefinitionScript.Split(new [] { Environment.NewLine },
StringSplitOptions.RemoveEmptyEntries);
回答by Rubens Farias
try this:
尝试这个:
List<string> list = new List<string>(Regex.Split(input, Environment.NewLine));
回答by SAL
Minor addition:
次要添加:
List<string> list = new List<string>(
input.Split(new string[] { "\r\n", "\n" },
StringSplitOptions.None));
will catch the cases without the "\r" (I've many such examples from ancient FORTRAN FIFO codes...) and not throw any lines away.
将捕获没有“\r”的情况(我有很多来自古老的 FORTRAN FIFO 代码的这样的例子......)并且不会丢弃任何行。