Recipe2.25.Appending a Line


Recipe 2.25. Appending a Line

Problem

You need to append a line, including a line terminator, to the current string.

Solution

Use 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 

Discussion

The 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 Also

See the "StringBuilder.AppendLine Method" topic in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net