- Preparing Your Machine to Work with Strings
- Working with Strings
- Initializing Strings
- Comparing Strings
- Concatenating Strings
- Finding the String Length
- Comparing and Concatenating Strings in the Sample Application
- Creating Strings from Characters
- Using Escape Characters
- Using Literal Strings
- Accessing the String's Characters
- Finding a Substring within a String
- Extracting Part of the String
- Splitting a String
- Joining a String
- Uppercasing and Lowercasing
- Formatting Strings
- Finishing the Sample Application
- Representing Objects as Strings
- Allocating Strings with StringBuilder
Formatting Strings
Formatting enables you to define templates for strings. The template tells the string class the text that doesn't change. In the template you also specify placeholders for the text that does change. The string class then fills in the placeholders with text that you provide. This makes it easier for you, because the string class does the hard work of concatenating the parts of fixed text with the parts of variable text.
To format strings:
Type string str where str is the name of the string that will hold the formatted text.
Type =string.Format(.
Type a formatting string enclosed in quotes. The formatting string tells the string class the fixed text.
Within the formatting string, type {0}, {1}, {2}, etc. to set placeholders for the variable text. For example: "LastName={0} and FirstName={1}".
Type a comma.
Type the name of the variable that contains the dynamic text for the string.
Repeat steps 5 and 6 for each placeholder in step 4.
Type ); to end the statement (Figure 4.56).
Figure 4.56 If you don't specify a delimiter character, Split uses spaces and carriage returns as delimiters.
Tip
You can use the same placeholder more than once. For example, if you were writing a form letter, you could repeat the recipient's name more than once. To accomplish that you simply use the placeholder string, for example {0} more than once (Figure 4.57).
Figure 4.57 Each placeholder has an index number. You can insert the same word in many places in the string if you repeat the index number that corresponds to the word.