- Jun 6, 2003
- 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
Using Literal Strings
Table 4.1 showed a list of special characters. These characters are characters that must be represented using the escape character (\). In C# it is also possible to create literal strings. Literal strings enable you to use special characters like the backslash or double quotes without having to use special codes or the escape character.
To create a literal string:
Type string str where str is the name of the variable to hold the string.
Type = @"the string"; (the @ character followed by double quotes, followed by any string context, followed by another double quote) (Figure 4.36).
Figure 4.36 Literal strings enable you to represent special characters without using escape sequences.
You can use backslashes in literal strings without having to use two backslashes (Figure 4.37).
Figure 4.37 Because the backslash is used to represent escape sequences, to add a backslash you need to type two backslashes. However, with literal strings you don't use escape sequences, so you can use the backslash as a backslash.
To specify the double-quote character you can put two double-quote characters together (Figure 4.38).
Figure 4.38 The double-quote character is a problem no matter what type of string you use, because it tells the compiler where the string begins and ends. With literal strings to use a double quote as part of the string all you have to do is put two double quotes together.
If you use literal strings you can split a string into multiple lines of code; however, keep in mind that doing so inserts a carriage return character into the string (Figure 4.39).
Figure 4.39 When you break a literal strings into multiple lines the carriage returns you put in the editor are preserved. However, they aren't visible in HTML because white space is condensed into a single space.
The rules for when white space is preserved, which we discussed in the previous section, also apply to literal strings.