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 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.
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
596906c14.indd 175 4/7/10 12:32:52 PM
176
LESSON 14 Working With StringS
METHOD PURPOSE
LastIndexOf
Returns the index of the last occurrence of a target character or string
within the string.
LastIndexOfAny
Returns the index of the last occurrence of any of a set of characters in
the string.
PadLeft
Pads the string to a given length by adding characters on the left if
necessary.
PadRight
Pads the string to a given length by adding characters on the right if
necessary.
Remove
Removes a piece of the string.
Replace
Replaces occurrences of a string or character with new values within
the string.
Split
Splits the string apart at a delimiter (for example, commas) and returns
an array containing the pieces.
StartsWith
Returns true if the string starts with a target string.
Substring
Returns a substring.
ToLower
Returns the string converted to lowercase.
ToUpper
Returns the string converted to uppercase.
Trim
Removes leading and trailing characters from the string. An overloaded
version that takes no parameters removes whitespace characters
(space, tab, newline, and so on).
TrimEnd
Removes trailing characters from the string.
TrimStart
Removes leading characters from the string.
Remember that string indexing starts with 0 so the first letter has index 0, the
second has index 1, and so forth.
In addition to all of these methods, the string class provides a very useful Length property. As you
can probably guess,
Length returns the number of characters in the string.
The
string class also provides the useful static (shared) methods Format and Join. A static method
is one that is provided by the class itself rather than an instance of the class. You invoke a static
method using the class’s name instead of a variable’s name.
TABLE 141
(continued)
596906c14.indd 176 4/7/10 12:32:53 PM
Format and ToString
177
The Format method formats a series of parameters according to a format string and returns a new
string. For example, the following code uses the
string class’s Format method to display the values
in the variables
x and y surrounded by parentheses and separated by a comma:
int x = 10, y = 20;
string txt = string.Format(“({0}, {1})“, x, y);
The following text shows the result:
(10, 20)
The next section says more about the Format method.
The
Join method does the opposite of the Split method: it joins a series of strings, separating
them with a delimiter. Lesson 16 says more about arrays and provides some examples that use
Split and Join.
FORMAT AND TOSTRING
The string class’s Format method builds a formatted string. Its first parameter is a format string
that tells how the method should display its other parameters. The format string can contain literal
characters that are displayed as they appear, plus formatting fields.
Each field has the following syntax:
{index[,alignment][:formatString]}
The curly braces are required. The square brackets indicate optional pieces.
The key pieces of the field are:
index
The zero-based index of the Format method’s parameters that should be displayed
by this field.
alignment
The minimum number of characters that the field should use. If this is negative,
the field is left-justified.
formatString
The format string that indicates how the field’s value should be formatted.
The following format sections describe some of the many values that you can use here in addi-
tion to literal characters.
For example, the following code defines a
string and two decimal values. It then uses
Console.WriteLine to display a string built by string.Format in the Output window.
string itemName = “Fiendishly Difficult Puzzles”;
decimal quantity = 2M;
decimal price_each = 9.99M;
Console.WriteLine(
string.Format(“You just bought {1} {0} at {2:C} each.”,
itemName, quantity, price_each));
The format string is “You just bought {1} {0} at {2:C} each.”
596906c14.indd 177 4/7/10 12:32:53 PM
178
LESSON 14 Working With StringS
The first field is {1}. This displays parameter number 1 (the second parameter remember they’re
zero-based).
The second field is
{0}. This displays the first parameter.
The third field is
{2:C}. This displays the third parameter with the format string C, which formats
the value as currency.
The result is:
You just bought 2 Fiendishly Difficult Puzzles at $9.99 each.
The following code shows an example that uses field widths to make values line up in columns.
Before the code executes, assume that
itemName1, quantity1, and the other variables have already
been initialized.
Console.WriteLine(
string.Format(“{0,-20}{1,5}{2,10}{3,10}“,
“Item”, “Qty”, “Each”, “Total”)
);
Console.WriteLine(
string.Format(“{0,-20}{1,5}{2,10:C}{3,10:C}“,
itemName1, quantity1, priceEach1, quantity1 * priceEach1)
);
Console.WriteLine(
string.Format(“{0,-20}{1,5}{2,10:C}{3,10:C}“,
itemName2, quantity2, priceEach2, quantity2 * priceEach2)
);
Console.WriteLine(
string.Format(“{0,-20}{1,5}{2,10:C}{3,10:C}“,
itemName3, quantity3, priceEach3, quantity3 * priceEach3)
);
Notice that the code begins with a line that defines the column headers. Its formatting string uses
the same indexes and alignment values as the other formatting strings so the headers line up with the
values below.
The following shows the result:
Item Qty Each Total
Pretzels (dozen) 4 $5.95 $23.80
Blue laser pointer 1 $149.99 $149.99
Titanium spork 2 $8.99 $17.98
Because the format string is just a string, you could dene it in a constant or
variable and then use that variable as the first argument to the
Format method.
That way you are certain that all of the
Format statements use the same string.
This also makes it easier to change the format later if necessary.
Every object provides a ToString method that converts the object into a string. For simple data types
such as numbers and dates, the result is the value in an easy-to-read string.
596906c14.indd 178 4/7/10 12:32:53 PM
Format and ToString
179
The ToString method for some objects can take a format parameter that tells how you want the item
formatted. For example, the following statement displays the variable
cost formatted as a currency
value in the Output window:
Console.WriteLine(cost.ToString(“C”));
The following sections describe standard and custom format strings for numbers, dates, and
times. You can use these as arguments to the
ToString method or as the formatString part of
the
string.Format method’s format strings.
Standard Numeric Formats
Formatting characters tell string.Format and ToString how to format a value. For the characters
discussed in this section, you can use either an uppercase or lowercase letter. For example, you can
use
C or c for the currency format.
Table 14-2 summarizes the standard numeric formatting characters.
TABLE 142
CHARACTER MEANING EXAMPLE
C Currency with a currency symbol, thousands separators,
and a decimal point.
$12,345.67
D Decimal. Integer types only. 12345
E Scientific notation. 1.234567E+004
F Fixed-point. 12345.670
G General. Either fixed-point or scientific notation, whichever
is shorter.
12345.67
N Similar to currency except without the currency symbol. 12,345.67
P Percent. The number is multiplied by 100 and a percent sign
is added appropriately for the computer’s locale. Includes
thousands separators and a decimal point.
123.45 %
R Round trip. The number (double or float only) is formatted
in a way that guarantees it can be parsed back into its
original value.
1234.567
X Hexadecimal. 3A7
You can follow several of these characters with a precision specifier that affects how the value is
formatted. How this value works depends on the format character that it follows.
For the D and X formats, the result is padded on the left with zeros to have the length given by the
precision specifier. For example, the format D10 produces a decimal value padded with zeros to
10 characters.
596906c14.indd 179 4/7/10 12:32:54 PM
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.17.140