string
MethodsClass string
provides several methods that return modified copies of string
s. Figure 16.8 demonstrates string
methods Replace
, ToLower
, ToUpper
and Trim
.
Line 20 uses string
method Replace
to return a new string
, replacing every occur-rence in string1
of character 'e'
with 'E'
. Method Replace
takes two arguments—a char
for which to search and another char
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
. An overloaded version of this method allows you to provide two string
s as arguments.
The string
method ToUpper
generates a new string
(line 24) that replaces any lower-case letters in string1
with their uppercase equivalents (using the current culture’s rules). 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 25 uses string
method ToLower
to return a new string
in which any uppercase letters in string2
are replaced by their lowercase equivalents (using the current culture’s rules). The original string
is unchanged. As with ToUpper
, if there are no characters to convert to lowercase, method ToLower
returns the original string
.
Line 29 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 and trailing whitespace characters. This method is particularly useful for retrieving user input (i.e., via a TextBox
). Another version of method Trim
takes a character array and returns a copy of the string
that does not begin or end with any of the characters in the array argument.