Edward Tanguay
Edward Tanguay

Reputation: 193432

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:

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

Upvotes: 27

Views: 50086

Answers (4)

SAL
SAL

Reputation: 1260

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.

Upvotes: 6

Rubens Farias
Rubens Farias

Reputation: 57996

try this:

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

Upvotes: 19

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158379

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.

Upvotes: 45

bruno conde
bruno conde

Reputation: 48255

Use the overload of string.Split that takes a string[] as separators:

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

Upvotes: 8

Related Questions