Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to append newline to string except for last

I was looking for the best/cleanest way to iterate over a list of strings and then create a single string of those separated by newlines (except for the last). Like so:

String 1 String 2 String 3 

I have written two loops here which has a newline at the end of the string (which I want to avoid) and another that does not. The one does not just doesn't seem "clean" to me. I would think there would be a simpler way to do it so that the logic is nearly as simple as in the example that has a new line to the end of the string.

List<string> errorMessages = new List<string>(); string messages = "";  //Adds newline to last string. Unwanted. foreach(string msg in errorMessages) {     messages += msg + "\n"; }  messages = ""; bool first = true;  //Avoids newline on last string foreach (string msg in errorMessages) {     if(first)     {         first = false;         messages = msg;     }     else     {         messages += "\n" + msg;     } } 

Maybe it is wishful thinking, but I would have thought this was a common enough occurrence to warrant a better way to accomplish my goal.

like image 548
Justin Avatar asked Jan 03 '13 13:01

Justin


People also ask

How do you add a new line to a string join?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

Does \n work in a string?

in a string prevents actually making a new line and instead of Type (new line) for a new line it is Type \n for a new line .

How do you split in newline?

Split String at Newline Split a string at a newline character. When the literal \n represents a newline character, convert it to an actual newline using the compose function. Then use splitlines to split the string at the newline character. Create a string in which two lines of text are separated by \n .

How do you add a new line to a string in Python?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.


1 Answers

Use join

string.Join(System.Environment.NewLine, errorMessages); 
like image 156
MrFox Avatar answered Sep 16 '22 20:09

MrFox