【问题标题】:How to remove all newlines in an array without using for loop with C#如何在不使用 C# 循环的情况下删除数组中的所有换行符
【发布时间】:2014-09-14 12:41:19
【问题描述】:

我想在不使用for 循环的情况下删除所有换行符,然后数组可能会更改顺序。代码必须在下面注释的代码行。

string[] filterInput1 = tbInput1.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
//(remove all Environment.NewLine or "" code goes here).
string after_resultInput1 = "";
for (int i = 0; i < filterInput1.Length; i++)
{
    string[] getDict = filterInput1[i].Split(new char[] { Convert.ToChar(tbDelim.Text) });
    after_resultInput1 += getDict[Convert.ToInt32(tbColumn.Text)] + Environment.NewLine;
}

Split()后filterInput1的数组

filterInput1
{string[6]}
[0]: "asdasdasd|abc"
[1]: ""
[2]: ""
[3]: "1111"
[4]: ""
[5]: ""

结果必须是:

filterInput1
{string[2]}
[0]: "asdasdasd|abc"
[1]: "1111"

【问题讨论】:

    标签: c# asp.net arrays


    【解决方案1】:

    试试StringSplitOptions.RemoveEmptyEntries:

    string[] filterInput1 = tbInput1.Text.Split(
        new string[] { Environment.NewLine },
        StringSplitOptions.RemoveEmptyEntries
    );
    

    【讨论】:

      【解决方案2】:

      试试 AlexD 建议的 RemoveEmptyEntries:

      string[] filterInput1 = tbInput1.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
      

      祝你任务顺利。

      如果你允许 linq,你可以这样做:

      after_resultInput1 = string.Join(Environment.NewLine, 
          tbInput1.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).
          SelectMany(s => s.Split(new char[] { Convert.ToChar(tbDelim.Text) })));
      

      祝你好运。

      【讨论】:

      • 感谢您对 LINQ 的补充意见。哪个跑得更快?
      • 这个比你的运行得更快,因为你的使用 += 而我的示例使用 string.Join,而后者又使用 StringBuilder。这就是理论,但在你的情况下,没有人会注意到。
      • 由于数组的数量很大,我正在寻找解决上述问题的最佳解决方案以及最快的代码。再次感谢您,您的代码加上额外的代码非常棒。
      • @PMay1903:回答“哪个跑得更快?”总是一样的:拿出一个秒表,双向运行代码,然后你就会知道了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-15
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 2022-01-22
      相关资源
      最近更新 更多