Ad

How To Split A String Into A List From A Multi-line TextBox That Adds '\n\r' As Line Endings?

- 1 answer

I've got a textbox in my XAML file:

<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>).

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:

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>?

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad