
Working with Strings
Previous lessons provided a sneak peek at some of the things that a C# program can do with
strings. Lesson 11 explained how you can use the
+ operator to concatenate two strings. Several
lessons show how to use the
ToString method to convert numeric values into strings that you
can then display to the user.
In this lesson, you learn a lot more about strings. You learn about
string class methods that
let you search strings, replace parts of strings, and extract pieces of strings. You also learn new
ways to format numeric and other kinds of data to produce strings.
STRING METHODS
The string class provides a lot of useful methods for manipulating strings. For example, the
EndsWith method returns true if a string ends with a particular substring. The following
code determines whether a string ends with the substring
dog:
string str = “The quick brown fox jumps over the lazy dog.”;
MessageBox.Show(“Ends with \“dog.\“: “ + str.EndsWith(“dog.”));
Table 14-1 summarizes the string class’s most useful methods.
TABLE 141
METHOD PURPOSE
Contains
Returns true if the string contains a target string.
EndsWith
Returns true if the string ends with a target string.
IndexOf
Returns the index of a target character or string within the string.
IndexOfAny
Returns the index of the first occurrence of any of a set of characters in
the string.
Insert
Inserts text in the middle of the string.
14
continues ...