Before examining the other string classes, this section quickly reviews some of the available methods on the String class.
System.String is a class specifically designed to store a string and allow a large number of operations on the string. Also, because of the importance of this data type, C# has its own keyword and associated syntax to make it particularly easy to manipulate strings using this class.
You can concatenate strings using operator overloads:
string message1 = "Hello"; // returns "Hello" message1 += ", There"; // returns "Hello, There" string message2 = message1 + "!"; // returns "Hello, There!"
C# also allows extraction of a particular character using an indexer-like syntax:
char char4 = message[4]; // returns 'a'. Note the char is zero-indexed
This enables you to perform such common tasks as replacing characters, removing whitespace, and capitalization. The following table introduces the key methods.
Method | Purpose |
---|---|
Compare | Compares the contents of strings, taking into account the culture (locale) in assessing equivalence between certain characters |
CompareOrdinal | Same as Compare but doesn't take culture into account |
Concat | Combines separate string instances into a single instance |
CopyTo | Copies a specific number of characters from the selected index to a entirely new instance of an array |
Format | Formats a string containing various values and specifiers for how each value should be formatted |
IndexOf | Locates the first occurrence of a given substring or character in the string |
IndexOfAny | Locates the first occurrence of any one of a set of characters in the string |
Insert | Inserts a string instance into another string instance at a specified index |
Join | Builds a new string by combining an array of strings |
LastIndexOf | Same as IndexOf, but finds the last occurrence |
LastIndexOfAny | Same as IndexOfAny, but finds the last occurrence |
PadLeft | Pads out the string by adding a specified repeated character to the left side of the string |
PadRight | Pads out the string by adding a specified repeated character to the right side of the string |
Replace | Replaces occurrences of a given character or substring in the string with another character or substring |
Split | Splits the string into an array of substrings, the breaks occurring wherever a given character occurs |
Substring | Retrieves the substring starting at a specified position in the string |
ToLower | Converts string to lowercase |
ToUpper | Converts string to uppercase |
Trim | Removes leading and trailing whitespace |