Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# ПІДРУЧНИКИ / c# / Hungry Minds - Visual C# Blueprint.pdf
Скачиваний:
101
Добавлен:
12.02.2016
Размер:
9.71 Mб
Скачать

C#

CREATE STRING LITERALS AND VARIABLES

Creating and manipulating strings is a big part of any programming language. Without programmatic storage of string variables, you cannot create a user

interface to your application without difficulty. For example, you need strings for describing entities such as a Client, where a Client has Company Name, Address, City, State, and ZIP Code fields. You cannot represent all these fields by a numeric value. These attributes are instead recognized through a series of characters.

When assigning values to a string variable, you can choose to use a verbatim string literal or a regular string literal. A verbatim string literal consists of an @ character followed by

zero or more characters inside of double-quote characters; for example, consider @"C:\temp\" a verbatim string literal. This type of assignment interprets the string verbatim. If you leave out the @ character, you are assigning a regular string literal. This assignment will not interpret verbatim, but will evaluate the string for escape sequences as it stores the string. The escape sequences are a backslash followed by a reserved set of single characters. These escape sequences will have an impact on the string that is formatted in the user interface. For example, in the string

"First Name\tLast Name" the \t will put a tab between the second and third word in the string.

CREATE STRING LITERALS AND VARIABLES

Create a new console application and open the

Class1.cs file.

¤ Rename the namespace to

StringSample.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Rename the class name to

 

ˇ Add an entry point to the

 

 

LiteralsAndVariables.

class by adding the Main

Save the file.

function.

 

Á Create a regular string to

 

 

 

 

 

 

 

 

hold the Web site name and

 

 

motto using \n to specify a

 

 

new line.

Create a verbatim string to hold the Web site location by adding the @ symbol before the string value.

° Write a message about the regular string.

You can use verbatim strings to avoid having characters interpreted as escape sequences. This is especially important for strings that hold file paths, for example, string sFilePath = @"c:\temp\ myfile.txt". The following escape sequences are the only ones allowed:

 

ESCAPE SEQUENCE

APPLIED FORMATTING

 

 

 

 

 

 

\'

Single quote

 

 

 

 

 

 

\"

Double-quote

 

 

 

 

 

 

\\

Backslash

 

 

 

 

 

 

\0

Null

 

 

 

 

 

 

\a

Alert

 

 

 

 

 

 

\b

Backspace

 

 

 

 

 

 

\f

Form feed

 

 

 

 

 

 

\n

New line

 

 

 

 

 

 

\r

Carriage return

 

 

 

 

 

 

\t

Horizontal tab

 

 

 

 

 

 

\u and \U

Unicode-escape-sequence *

 

 

 

 

 

 

\x

Hexadecimal-escape-sequence

 

 

 

 

 

* (For example, \u005C is “\”)

WORKING WITH STRINGS 8

If any other character follows a backslash in a regular string, a compile-time error occurs. For example, \z in a regular string (like "Brian\zErwin") creates a compiletime error because z is not a valid character for an escape sequence.

· Use the WriteLine method to output the regular string.

Use the WriteLine method to output an extra line.

Use the WriteLine method to output a message about the verbatim string.

± Use the WriteLine method to output the regular string.

¡ Set a debug stop at the end of the class.

Press F5 to save, build, and run the console application.

The regular string appears.

The verbatim string appears.

159

C#

ASSIGN VALUES TO STRINGS

You can assign and reassign literals to string variables, but you can benefit from knowing what goes on behind the scenes.

The String class in the .NET Framework is an immutable, fixed-length string of Unicode characters. Immutable means that the string cannot change. The String is a class and it is not only storage, but it also has capabilities (properties, methods, and fields) that allow manipulation of strings. In the case of changing an existing String, when a new value is assigned to an existing String you are not updating the object. The updated value is returned in a new instance of a String object.

This String class implements the IComparable,

ICloneable, IConvertible, and IEnumerable interfaces. These interfaces, along with the specific implementation in the String Class, give String objects the ability to do things like: convert String objects to other data types, evaluate parts of a string, format a string, and iterate through collections of String objects.

Assigning values to a String variable is similar to any other type of variable assignment. You can take two approaches, which are allocating a String variable and then assigning the value. This requires two separate lines of code. To shorthand this two-step process, you can assign a value to the String on the same line.

ASSIGN VALUES TO STRINGS

Rename the class to

AssignmentAndLength.

Save the file.

ˇ Add the Main function.

Á Create a string variable for the greeting and initialize the greeting.

Create an integer variable and initialize it using the Length property of the string created.

WORKING WITH STRINGS 8

Spaces do count when assigning strings.

TYPE THIS:

using System; namespace StringSample

{

class AssignmentAndLength

{

static void Main()

{

String sSpacesCount = " 6789";

int iSpacesCount = sSpacesCount.Length;

Console.WriteLine (

"The greeting: \n{0}\nis {1} characters long.", sSpacesCount, iSpacesCount);

}

}

}

RESULT:

C:\>csc AssignStrings_ai.cs C:\> AssignStrings_ai.exe The greeting:

6789

is 9 characters long. C:\>

° Use the WriteLine method to output the greeting and the length of the greeting.

· Set a debug stop

Press F5 to save, build, and run the console application.

A message about the length of the string appears.

161

Соседние файлы в папке c#