Lesson 14

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 a data type’s Parse method to convert a string into a number and how to 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 14.1

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.
IndexOfAn y Returns the index of the first occurrence of any of a set of characters in the string.
Insert Inserts text in the middle ...

Get C# 24-Hour Trainer, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.