I've got a textbox in my XAML file:
<TextBox
VerticalScrollBarVisibility="Visible"
AcceptsReturn="True"
Width="400"
Height="100"
开发者_如何学Python 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>
?
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.
try this:
List<string> list = new List<string>(Regex.Split(input, Environment.NewLine));
Use the overload of string.Split
that takes a string[]
as separators:
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.
精彩评论