0

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?

4 Answers 4

2

using LINQ

str1 = str1.Select(e => e.EndsWith("\n") ? e : e + "\n")
           .ToArray();
Sign up to request clarification or add additional context in comments.

Comments

1

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


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

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

1 Comment

This approach also removes e.g. space at the beginning of each element how about str1 = str1.Select(x => x.TrimEnd('\n') + "\n").ToArray();
1

Using a for loop, you may do something like this:

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

Comments

0
 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(',');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.