Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

string

c#

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

like image 807
Edward Tanguay Avatar asked Nov 12 '09 15:11

Edward Tanguay


People also ask

How do I split a string over multiple lines?

You can have a string split across multiple lines by enclosing it in triple quotes. Alternatively, brackets can also be used to spread a string into different lines. Moreover, backslash works as a line continuation character in Python. You can use it to join text on separate lines and create a multiline string.

How split a string after a specific character in C#?

Split(char[], StringSplitOptions) Method This method is used to splits a string into substrings based on the characters in an array. You can specify whether the substrings include empty array elements. Syntax: public String[] Split(char[] separator, StringSplitOptions option);

Can you split a string into a list C#?

The String. Split() splits the main string into multiple sub-strings and returns them in the form of a string array. The array of strings returned by the String. Split() method can be converted into a list by using the ToList() function of Linq in C#.


1 Answers

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.

like image 192
Fredrik Mörk Avatar answered Sep 21 '22 19:09

Fredrik Mörk