简体   繁体   English

如何将字符串拆分为List <string> 从多行TextBox添加&#39;\\ n \\ r&#39;作为行结尾?

[英]How to split a string into a List<string> from a multi-line TextBox that adds '\n\r' as line endings?

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 '结尾的字符串解析为List<string>

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"替换为适合您需要的分隔符字符串。

尝试这个:

List<string> list = new List<string>(Regex.Split(input, Environment.NewLine));

Use the overload of string.Split that takes a string[] as separators: 使用string.Split的重载, string.Split string[]作为分隔符:

itemTypeDefinitionScript.Split(new [] { Environment.NewLine }, 
                               StringSplitOptions.RemoveEmptyEntries);

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 \\ n”的情况下捕获这些情况(我从古代FORTRAN FIFO代码中获得了很多这样的例子......)并且不会丢弃任何行。

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

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