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

C#

CONCATENATE STRINGS

Concatenating, or joining, strings is a common task for building useful strings. Most of the time, you build strings from more than one source. Values for strings

can come from a combination of sources (database calls, constants, integer counters, and so on).

To build out a string from multiple sources, you concatenate these strings in a specified sequence. You can accomplish the concatenate of two or more string sources in several ways. You can use the arithmetic operator (+) or the (+=) assignment operator. Use the arithmetic operator (+) to combine strings in the order that they appear in the

expression, or use the assignment operator (+=) to append a string to an existing string. As you append your strings, you have to include the spacing inside the double-quotes of your string.

You can also use the Concat method on the String class to perform concatenation. With this method, you can concatenate one or more String classes together and get a new String returned to you. Another overloaded implementation of the String Class allows you to pass a string array, which is handy if you have many strings to concatenate into one representative string.

CONCATENATE STRINGS

Change the class name to

Concatenate.

Save the file.

ˇ Add the Main function.

Á Create a string variable and initialize the string with a name.

Create another string variable and initialize the string with a greeting.

WORKING WITH STRINGS 8

Knowing that the String object is immutable and that it returns a new instance of a String object, you may want to explore the

System.Text.StringBuilder framework class. The

StringBuilder class lets you concatenate strings without having to create a new object each time you modify the string. The StringBuilder class also gives you more flexibility with concatenating, like appending versus inserting.

TYPE THIS:

using System; using System.Text;

namespace StringSample

{

class Concatenate

{

static void Main()

{

StringBuilder sbPersonalGreeting =

new StringBuilder("Hello, how are you today");

sbPersonalGreeting.Insert(0,"Danny - "); sbPersonalGreeting.Append("?");

Console.WriteLine(sbPersonalGreeting);

}

}

}

RESULT:

C:\> csc ConcatenateStrings_ai.cs

C:\> ConcatenateStrings_ai.exe

Danny – Hello, how are you today?

C:\>

° Create a new string variable and initialize the variable by using the

String.Concat function and the two strings previously created.

· Write the resulting string to the console.

Set a debug stop.

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

A message appears showing the concatenated string.

163

C#

COMPARE STRINGS

Comparing strings in code is useful when performing logical operations. String comparisons are useful in expressions that are used for an if or switch

statement. For example, you can use a string comparison when someone is logging onto your Web site. You can compare the password that the user entered to the password in the database.

There are several comparison methods for a string, the simplest being two equals signs (==), which is the equality operator. This operator checks to see if the two strings hold the same value (length, characters, and sequence of characters).

The String class contains some very useful comparison methods — Compare, CompareOrdinal, CompareTo, StartsWith, EndsWith, Equals, IndexOf, and

LastIndexOf. The method you choose depends on if you are looking for a binary response (for example, getting a true or false for the presence of a substring, or if both strings match based on the method’s criteria) or position of where a substring exists.

With the Compare method, the comparison is done in the expression of the if statement. Note that it returns an integer, which is used in a comparison to zero. If zero is returned, then a match is found.

COMPARE STRINGS

Rename the class name to

Compare.

Save the file.

to

ˇ Add the Main function.

Á Use the WriteLine method to prompt the user for the password.

Create a string variable that is initialized with the value that is read from the console.

° Create a string variable for the password and set the password.

WORKING WITH STRINGS 8

Another way to approach string comparisons is to run the CompareTo method on the first string variable and give it the second string variable as the parameter to that method.

TYPE THIS:

using System;

namespace StringSample

{

class Compare

{

static void Main()

{

Console.WriteLine("Please enter your password " + "to enter the specified Photo Gallery:");

string sPassword = Console.ReadLine(); string sDatabasedPassword = "opensaysme";

if (sDatabasedPassword.CompareTo(sPassword)==0) Console.WriteLine("You can view the photos");

else

Console.WriteLine("You do not have permission" + " to view the photos");

}

}

}

RESULT:

C:\>csc CompareStrings.cs

C:\> CompareStrings.exe

Please enter your password to enter the specified Photo Gallery.

Opensaysme

You can view the photos.

c:\>

· Check the password using an if statement and write a message to the console if the password matches.

Use an else statement if the password does not match and write another message to the console.

Set a debug stop.

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

A message prompting for the password appears.

¡ Type in the password of opensaysme.

A message about being able to view the photos appears.

165

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