tags:

views:

241

answers:

3

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

+2  A: 

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

itemTypeDefinitionScript.Split(new [] { Environment.NewLine }, 
                               StringSplitOptions.RemoveEmptyEntries);
bruno conde
+3  A: 

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.

Fredrik Mörk
excellent, that's it, thanks!
Edward Tanguay
+1  A: 

try this:

List<string> list = new List<string>(Regex.Split(input, Environment.NewLine));
Rubens Farias
+1 for the only solution that preserves blank lines.
Frank Krueger