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.
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.
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 .
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 .
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.
Use join
string.Join(System.Environment.NewLine, errorMessages);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With