Summary

  • C# strings can be sorted, searched, and otherwise manipulated.

  • The String class is sealed, meaning it cannot be derived from. It implements the IComparable, ICloneable, IConvertible, and IEnumerable interfaces, indicating that you can compare two strings (to sort them), clone a string (to create a duplicate), convert a string to another type (for example, converting the string “15” to the integer 15), and enumerate over a string using a foreach statement, respectively.

  • A string literal is a quoted string of characters assigned to a variable of type string. This is the most common use of strings.

  • Escape characters allow you to add special characters to strings that you would otherwise not be able to represent.

  • A verbatim string literal starts with an @ symbol and indicates that the string should be used exactly as is. Verbatim strings do not require escape characters.

  • You can concatenate strings with the Concat( ) method or the + operator.

  • You can copy strings with the Copy( ) method or the = operator.

  • You can test for equality of two strings with the Equals( ) method or the == operator.

  • The String class also includes methods for finding and extracting substrings, such as IndexOf( ), LastIndexOf( ), and Substring( ).

  • You can use the Split( ) method with an array of delimiters to divide a string into substrings.

  • Strings are immutable. Every time you appear to modify a string, a copy is made with the modification and the original string is released to the garbage collector.

  • The StringBuilder class allows you to assemble the contents of a string with greater efficiency and then to call its ToString( ) method to generate the string you need once it is fully assembled.

  • Regular expressions provide pattern-matching abilities that enable you to search and manipulate text.

Although you’ve seen and used strings throughout this book, this chapter should give you an indication of just how powerful and flexible the String class is. However, now that you have the ability to let users enter strings instead of just integers or single characters, you open yourself up to the possibility that your users could provide some input that you can’t handle. The more you interact with users, the greater the odds that they’ll do something you didn’t expect, and that could break your code. Fortunately, that doesn’t have to be a disaster. C# provides an Exception class that allows you to anticipate certain types of errors, and take the appropriate action when they occur.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset