The String Type
One of the best examples of how class members can replace built-in functions is found with strings. In the past, every language has defined its own specialized functions for string manipulation. In .NET, however, you use the methods of the String class, which ensures consistency between all .NET languages.
The following code snippet shows several ways to manipulate a string using its object nature:
string myString = "This is a test string ";
myString = myString.Trim(); // = "This is a test string"
myString = myString.Substring(0, 4); // = "This"
myString = myString.ToUpper(); // = "THIS"
myString = myString.Replace("IS", "AT"); // = "THAT"
int length = myString.Length; // = 4
The first few statements use built-in methods, such as Trim(), Substring(), ToUpper(), and Replace(). These methods generate new strings, and each of these statements replaces the current myString with the new string object. The final statement uses a built-in Length property,which returns an integer that represents the number of characters in the string.
Note that the Substring() method requires a starting offset and a character length. Strings use zero-based counting. This means that the first letter is in position 0, the second letter is in position 1, and so on. You'll find this standard of zero-based counting throughout the .NET Framework for the sake of consistency. You've already seen it at work with arrays. You can even use the string methods in succession in a single (rather ugly) line:
myString = myString.Trim().Substring(0, 4).ToUpper().Replace("IS", "AT");
Or, to make life more interesting, you can use the string methods on string literals just as easily as string variables:
myString = "hello".ToUpper(); // Sets myString to "HELLO"
Table lists some useful members of the System.String class.

Join the conversation! Your thoughts help the community grow.