简体   繁体   English

如何在字符串数组的每个元素中添加新行?

[英]How to Append a new line in each element of a string array?

I am facing a problem with string array.我正面临字符串数组的问题。 please help me here.请在这里帮助我。 I have a string like below:我有一个像下面这样的字符串:

string[] str1;
str1 = new string[5]{ “Element 1”, “Element 2”, “Element 3”, “Element 4”, “Element 5” };

Here, I want to check each element in the string array has a new line or not.在这里,我想检查字符串数组中的每个元素是否有新行。 If it doesn't have a new line, append to it, I need to append the new line characters like below:如果它没有新行,请附加到它,我需要附加如下的新行字符:

str1 = new string[5]{ “Element 1\n”, “Element 2\n”, “Element 3\n”, “Element 4\n”, “Element 5\n” };

How to achieve this?如何实现这一目标?

using LINQ使用LINQ

str1 = str1.Select(e => e.EndsWith("\n") ? e : e + "\n")
           .ToArray();

If I understand the question如果我理解这个问题

Given给定的

var str1 = new string[5] { "Element 1", "Element 2", "Element 3", "Element 4", "Element 5" };

It could be as simple as它可以很简单

str1 = str1.Select(x => x.TrimEnd("\n") + "\n").ToArray();

Which makes sure every element has a "\\n" appended这确保每个元素都附加了一个“\\n”


or或者

str1 = str1.Select(x => x.EndsWith("\n") ? x : x + "\n").ToArray();

or或者

str1 = str1.Select(x => x.EndsWith(Environment.NewLine) ? x : x + Environment.NewLine).ToArray();

More Platform independent更独立于平台


As a guess, it's more than likely you just need to add the NewLine , when you are writing it to a textbox/file/Console, with string.Join , and can keep your array clean of that sort of thing作为猜测,当您使用string.Join将其写入文本框/文件/控制台时,您很可能只需要添加string.Join ,并且可以使您的数组保持清洁

Console.WriteLine(string.Join(Environment.NewLine, str));

Using a for loop, you may do something like this:使用for循环,您可以执行以下操作:

for (int i = 0; i < str1.Length; i++)
{
    if (!str1[i].EndsWith("\n"))
    {
        str1[i] += "\n";
    }
}

That being said, you should consider changing the name of your variable.话虽如此,您应该考虑更改变量的名称。 str1 isn't a good name for an array (or even for a string in most situations). str1不是数组的好名字(甚至在大多数情况下对于字符串)。

 string[] str1 = { "Element 1","Element 2", "Element 3", "Element 4", "Element 5" };
        string[] newstr1;
        var b="";
        for(int i=0;i<str1.Length;i++)
        {
            var chck1 = str1[i];
            if (!chck1.Contains("\n"))
            {

                b += chck1 +"\n ,";
            }
         }
        b = b.TrimEnd(',');
        var nwstrg = b.Split(',');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM