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 You can build a format string to serve as a template. In the format string you specify placeholders for each segment. The placeholders are specified with curly brackets.
string firstName = "Bill";
string lastName = "Smith";
string templ =
"Select * from contacts where ";
templ +=
"LastName={0} and FirstName={1}";
string SQL =
string.Format(templ,firstName,lastName);
Response.Write(SQL);
/*
outputs:
Select * from contacts where
LastName=Bill and FirstName=Smith
*/
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.
string company = "Federation";
string customer = "Chewbacca";
string templ = "Dear Mr.
{1}
,<br>";
templ += "Welcome to the
{0}
. ";
templ += "The
{0}
is glad that you have become ";
templ += "a warp capable species.";
string letter =
string.Format(templ,company,customer);
Response.Write(letter);
/*
outputs:
Dear Mr.
Chewbacca
,
Welcome to the
Federation
. The
Federation
is glad that you have become a warp capable species. */
|