如何使用C#在回车符上分割字符串?
我有一个ASP.NET页,其中包含一个名为txbUserName的多行文本框.然后,我将3个名称粘贴到文本框中,它们是垂直对齐的:
I have an ASP.NET page with a multiline textbox called txbUserName. Then I paste into the textbox 3 names and they are vertically aligned:
- Jason
- Ammy
- 凯伦
每当我检测到回车符或换行时,我都希望能够以某种方式获取名称并将其拆分为单独的字符串.我在想数组可能是要走的路. 有什么想法吗?
I want to be able to somehow take the names and split them into separate strings whenever i detect the carriage return or the new line. i am thinking that an array might be the way to go. Any ideas?
谢谢.
string[] result = input.Split(new string[] {"\n", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);
这涵盖了\ n和\ r \ n换行符类型,并删除了用户可能输入的任何空行.
This covers both \n and \r\n newline types and removes any empty lines your users may enter.
我使用以下代码进行了测试:
I tested using the following code:
string test = "PersonA\nPersonB\r\nPersonC\n";
string[] result = test.Split(new string[] {"\n", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in result)
Console.WriteLine(s);
它可以正常工作,并分为三个字符串数组,其中包含条目"PersonA","PersonB"和"PersonC".
And it works correctly, splitting into a three string array with entries "PersonA", "PersonB" and "PersonC".