Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Выполнение действия со строками с помощью основных строковых операций

В следующем примере некоторые методы, описанные в разделе Основные операции со строками, используются для создания класса, который выполняет обработку строк так же, как это происходит в реальном приложении. Класс MailToData хранит имя и адрес человека в отдельных свойствах и предоставляет способ объединения полей City, State и Zip в одну строку для отображения пользователю. Более того, данный класс позволяет пользователю вводить сведения о городе, области и почтовом индексе в одну строку. Приложение автоматически разбирает эту строку и вводит необходимые сведения в соответствующее свойство.

В этом упрощенном примере используется консольное приложение с интерфейсом командной строки.

Пример

------------

public class MailToData

{

string name = " ";

string address = " ";

string citystatezip = " ";

string city = " ";

string state = " ";

string zip = " ";

public MailToData()

{

}

public string Name

{

get{return name;}

set{name = value;}

}

public string Address

{

get{return address;}

set{address = value;}

}

public string CityStateZip

{

get

{

return ReturnCityStateZip();

}

set

{

citystatezip = value;

ParseCityStateZip();

}

}

public string City

{

get{return city;}

set{city = value;}

}

public string State

{

get{return state;}

set{state = value;}

}

public string Zip

{

get{return zip;}

set{zip = value;}

}

-----------

private void ParseCityStateZip()

{

int CityIndex;

int StateIndex;

// Check for an exception if the user did not enter spaces between

// the elements.

try

{

// Find index position of the space between

// city and state and assign that value to CityIndex.

CityIndex = citystatezip.IndexOf(" ");

// Initialize the CityArray to the value of the

// index position of the first white space.

char[] CityArray = new char[CityIndex];

// Copy the city to the CityArray.

citystatezip.CopyTo(0,CityArray ,0, CityIndex);

// Find index position of the space between

// state and zip and assign that value to CityIndex.

StateIndex = citystatezip.LastIndexOf(" ");

// Initialize the StateArray to the length of the state.

char[] StateArray = new char[StateIndex - CityIndex];

// Copy the state to the StateArray.

citystatezip.CopyTo(CityIndex, StateArray, 0, (StateIndex - CityIndex));

// Initialize the ZipArray to the length of the zip.

char[] ZipArray = new char[citystatezip.Length - StateIndex];

// Copy the zip to the ZipArray.

citystatezip.CopyTo(StateIndex, ZipArray, 0, (citystatezip.Length - StateIndex));

// Assign city to the value of CityArray.

city = new String(CityArray);

// Trim white spaces, commas, and so on.

city = city.Trim(new char[]{' ', ',', ';', '-', ':'});

// Assign state to the value of StateArray.

state = new String(StateArray);

// Trim white spaces, commas, and so on.

state = state.Trim(new char[]{' ', ',', ';', '-', ':'});

// Assign zip to the value of ZipArray.

zip = new String(ZipArray);

// Trim white spaces, commas, and so on.

zip = zip.Trim(new char[]{' ', ',', ';', '-', ':'});

}

// If an exception is encountered, alert the user to enter spaces

// between the elements.

catch(OverflowException)

{

Console.WriteLine("\n\nYou must enter spaces between elements.\n\n");

}

}

---------------

private string ReturnCityStateZip()

{

// Make state uppercase.

state = state.ToUpper();

// Put the value of city, state, and zip together

//in the proper manner.

string MyCityStateZip = String.Concat(city, ", ",

state, " ", zip);

return MyCityStateZip;

}

}

When the preceding code is executed, the user is asked to enter his or her name and address. The application places the information in the appropriate properties and displays the information back to the user, creating a single string that displays the city, state, and ZIP Code information.

------

При выполнении предыдущего кода пользователю предлагается ввести его имя и адрес. Приложение размещает сведения в соответствующих свойствах и отображает их для пользователя, создавая одну строку, в которой представлены сведения о городе, области и почтовом индексе.

Parsing Strings

The Parse method converts a string that represents a .NET Framework base type into an actual .NET Framework base type. Because parsing is the reverse operation of formatting (converting a base type into a string representation), many of the same rules and conventions apply. Just as formatting uses an object that implements the IFormatProvider interface to format the information into a string, parsing also uses an object that implements the IFormatProvider interface to determine how to interpret a string representation.

Parsing Numeric Strings

All numeric types have a static Parse method that you can use to convert a string representation of a numeric type into an actual numeric type. These methods allow you to parse strings that were produced using one of the formatting specifiers covered in Numeric Format Strings.

The characters used to represent currency symbols, thousand separators, and decimal points are defined in format providers. The Parse method accepts a format provider, allowing you to specify and explicitly parse culture-specific strings. If no format provider is specified, then the provider associated with the current thread is used.

The following code example converts a string to an integer value, increments that value, and displays the result.

string MyString = "12345";

int MyInt = int.Parse(MyString);

MyInt++;

Console.WriteLine(MyInt);

// The result is "12346".