Miscellaneous string Methods
Class string provides several methods that return modified copies of strings. The application in Fig. 16.8 demonstrates the use of these methods, which include string methods Replace, ToLower, ToUpper and trim.
Figure 16.8. string methods Replace, ToLower, ToUpper and TRim.
1 // Fig. 16.8: StringMethods2.cs 2 // Demonstrating string methods Replace, ToLower, ToUpper, Trim, 3 // and ToString. 4 using System; 5 6 class StringMethods2 7 { 8 public static void Main() 9 { 10 string string1 = "cheers!"; 11 string string2 = "GOOD BYE "; 12 string string3 = " spaces "; 13 14 Console.WriteLine( "string1 = "" + string1 + "" " + 15 "string2 = "" + string2 + "" " + 16 "string3 = "" + string3 + """ ); 17 18 // call method Replace 19 Console.WriteLine( 20 " Replacing "e" with "E" in string1: "" + 21 string1.Replace( 'e', 'E' ) + """ ); 22 23 // call ToLower and ToUpper 24 Console.WriteLine( " string1.ToUpper() = "" + 25 string1.ToUpper() + "" string2.ToLower() = "" + 26 string2.ToLower() + """ ); 27 28 // call Trim method 29 Console.WriteLine( " string3 after trim = "" + 30 string3.Trim() + """ ); 31 32 Console.WriteLine( " string1 = "" + string1 + """ ); 33 } // end method Main 34 } // end class StringMethods2
|
Line 21 uses string method Replace to return a new string, replacing every occurrence in string1 of character 'e' with 'E'. Method Replace takes two argumentsa string for which to search and another string with which to replace all matching occurrences of the first argument. The original string remains unchanged. If there are no occurrences of the first argument in the string, the method returns the original string.
string method ToUpper generates a new string (line 25) that replaces any lowercase letters in string1 with their uppercase equivalents. The method returns a new string containing the converted string; the original string remains unchanged. If there are no characters to convert, the original string is returned. Line 26 uses string method ToLower to return a new string in which any uppercase letters in string2 are replaced by their lowercase equivalents. The original string is unchanged. As with ToUpper, if there are no characters to convert to lowercase, method ToLower returns the original string.
Line 30 uses string method trim to remove all whitespace characters that appear at the beginning and end of a string. Without otherwise altering the original string, the method returns a new string that contains the string, but omits leading or trailing whitespace characters. Another version of method trim takes a character array and returns a string that does not contain the characters in the array argument.