Recipe 2.25. Appending a LineProblemYou need to append a line, including a line terminator, to the current string. SolutionUse the AppendLine method of the StringBuilder class: StringBuilder sb = new StringBuilder("First line of string"); // Terminate the first line. sb.AppendLine(); // Add a second line. sb.AppendLine("Second line of string"); This code will display the following: First line of string Second line of string DiscussionThe AppendLine method accepts a string and returns a reference to the same instance of the StringBuilder object on which this method was called. The string that is passed in to this method has a newline character or characters automatically appended on to the end of this string. The newline character(s) is dependent on the type of platform you are running. For example, Windows uses the \r\n carriage return and line-feed characters to represent a newline; on a Unix system the newline consists of only the line-feed character \n. You do not need to worry about this, as the AppendLine method knows which newline character(s) to apply. If you simply want to add several blank lines to your string, you can call AppendLine with no parameters. This effectively adds only a newline character to the current string in the StringBuilder object on which it was called. Calling this method with no parameter can also be used to add a newline character(s) to the current line, if the current line has no newline character(s). For example, the code in the Solution added a string with no newline character(s) to the instantiated StringBuilder object sb. You can then call sb.AppendLine( ) to force a newline character to be appended to this text. See AlsoSee the "StringBuilder.AppendLine Method" topic in the MSDN documentation. |