如何使用 C# 在回车时拆分字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1814562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:04:05  来源:igfitidea点击:

How to split strings on carriage return with C#?

c#text-manipulation

提问by Erica

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:

我有一个带有名为 txbUserName 的多行文本框的 ASP.NET 页面。然后我将 3 个名称粘贴到文本框中,它们垂直对齐:

  • Jason
  • Ammy
  • Karen
  • 杰森
  • 艾米
  • 凯伦

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?

我希望能够以某种方式获取名称并将它们拆分为单独的字符串,每当我检测到回车或新行时。我在想数组可能是要走的路。有任何想法吗?

thank you.

谢谢你。

采纳答案by jasonh

string[] result = input.Split(new string[] {"\n", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);

This covers both \n and \r\n newline types and removes any empty lines your users may enter.

这涵盖了 \n 和 \r\n 换行符类型,并删除了您的用户可能输入的任何空行。

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);

And it works correctly, splitting into a three string array with entries "PersonA", "PersonB" and "PersonC".

它工作正常,分成三个字符串数组,其中包含条目“PersonA”、“PersonB”和“PersonC”。

回答by Thanatos

String.Split?

String.Split?

mystring.Split(new Char[] { '\n' })

回答by TryCatch

Take a look at the String.Split function (not sure of exact syntax, no IDE in front of me).

看看 String.Split 函数(不确定确切的语法,我面前没有 IDE)。

string[] names = txbUserName.Text.Split(Environment.Newline);

回答by o.k.w

Replace any \r\nwith \n, then split using \n:

将 any 替换\r\n\n,然后使用 拆分\n

string[] arr = txbUserName.Text.Replace("\r\n", "\n").Split("\n".ToCharArray());

回答by Rubi

using System.Text;
using System.Text.RegularExpressions;


 protected void btnAction_Click(object sender, EventArgs e)
    {
        string value = txtDetails.Text;
        char[] delimiter = new char[] { ';','[' };
        string[] parts = value.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
        for (int i = 0; i < parts.Length; i++)
        {
            txtFName.Text = parts[0].ToString();
            txtLName.Text = parts[1].ToString();
            txtAge.Text = parts[2].ToString();
            txtDob.Text = parts[3].ToString();
        }
    }

回答by Tovich

Try this:

尝试这个:

message.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

Works if :

在以下情况下有效:

var message = "test 1\r\ntest 2";

Or

或者

var message = "test 1\ntest 2";

Or

或者

var message = "test 1\rtest 2";

回答by Chris J

It depends what you want to do. Another option, which is probably overkill for small lists, but may be more memory efficient for larger strings, is to use the StringReaderclass and use an enumerator:

这取决于你想做什么。另一个选项,对于小列表来说可能是矫枉过正,但对于较大的字符串可能更有内存效率,是使用StringReader类并使用枚举器:

IEnumerable<string> GetNextString(string input)
{
    using (var sr = new StringReader(input))
    {
        string s;
        while ((s = sr.ReadLine()) != null)
        {
            yield return s;
        }
    }
}

This supports both \nand \r\nline-endings. As it returns an IEnumerableyou can process it with a foreach, or use any of the standard linq extensions (ToList(), ToArray(), Where, etc).

这支持\n\r\n行尾。当它返回一个IEnumerable你可以用一个处理它foreach,或使用任何标准的LINQ扩展(ToList()ToArray()Where等)。

For example, with a foreach:

例如,使用foreach

var ss = "Hello\nworld\r\ntwo bags\r\nsugar";
foreach (var s in GetNextString(ss))
{
    Console.WriteLine("==> {0}", s);
}