Изменение содержимого строки 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

Изменение содержимого строки



Строки являются неизменяемыми, поэтому их содержимое изменить невозможно. Однако содержимое строки можно извлечь в форму для редактирования, выполнить изменения, а затем передать в новый экземпляр строки.

Пример

В следующем примере для извлечения содержимого строки в массив типа char используется метод ToCharArray. Затем некоторые элементы массива изменяются. После этого массив char используется для создания нового экземпляра строки.

ß---


How to: Determine Whether a String Contains a Numeric Value

To determine whether a string is a valid representation of a specified numeric type, use the static TryParse method. This method is implemented by all primitive numeric types and also by types such as DateTime and IPAddress. The following example shows how to determine whether "108" is a valid int.

int i = 0; string s = "108"; bool result = int.TryParse(s, out i); //i now = 108

If the string contains nonnumeric characters or the numeric value is too large or too small for the particular type you have specified, TryParse returns false and sets the out parameter to zero. Otherwise, it returns true and sets the out parameter to the numeric value of the string.

Note:
A string may contain only numeric characters and still not be valid for the type whose TryParse method that you use. For example, "256" is not a valid value for byte but it is valid for int. "98.6" is not a valid value for int but it is a valid decimal.

 


Определение наличия числового значения в строке

Чтобы определить, является ли строка допустимым представлением указанного числового типа, воспользуйтесь статическим методом TryParse. Этот метод реализован всеми простыми числовыми типами и такими типами, как DateTime и IPAddress. В следующем примере показано, как определить, является ли число 108 допустимым типом int.

int i = 0; string s = "108"; bool result = int.TryParse(s, out i); //i now = 108

Если строка содержит нечисловые знаки либо числовое значение слишком велико или мало для указанного типа, TryParse возвращает значение "false" и задает выходному параметру значение "0". В противном случае возвращается значение "true", а выходному параметру задается числовое значение строки.

Примечание.
Строка может содержать только числовые знаки и оставаться недопустимой для типа, где используется метод TryParse. Например, "256" не является допустимым значением для byte, однако оно допустимо для int. "98,6" не является допустимым значением для int, однако оно допустимо для decimal.

 


Example

The following examples show how to use TryParse with string representations of long, byte, and decimal values.

static void Main(string[] args) { string s = "1287543"; //"1287543.0" will return false for a long long number1 = 0; bool result = long.TryParse(s, out number1); if (result == true) Console.WriteLine("number1 now = {0}", number1); else Console.WriteLine("s is not a valid long");   byte number2 = 0; s = "255"; // A value of 256 will return false result = byte.TryParse(s, out number2); if (result == true) Console.WriteLine("number2 now = {0}", number2); else Console.WriteLine("s is not a valid byte");   decimal number3 = 0; s = "27.3"; //"27" is also a valid decimal result = decimal.TryParse(s, out number3); if (result == true) Console.WriteLine("number3 now = {0}", number3); else Console.WriteLine("number3 is not a valid decimal"); }

Robust Programming

Primitive numeric types also implement the Parse static method, which throws an exception if the string is not a valid number. TryParse is generally more efficient because it just returns false if the number is not valid.

Security

Always use the TryParse or Parse methods to validate user input from controls such as text boxes and combo boxes.


Пример

В следующем примере показано использование TryParse со строковыми представлениями значений long, byte и decimal.

ß--

 

 

Надежное программирование

Простые числовые типы также реализуют статический метод Parse, который вызывает исключение, если строка не является допустимым числом. TryParse обычно более эффективен, поскольку он просто возвращает значение "false", если число не является допустимым.

Безопасность

Для проверки данных, введенных пользователем в такие элементы управления, как текстовые поля и поля со списком, всегда следует использовать метод TryParse или Parse.


Encoding Base Types

Characters are abstract entities that can be represented using many different character schemes or code pages. For example, Unicode UTF-16 encoding represents characters as sequences of 16-bit integers, whereas Unicode UTF-8 represents the same characters as sequences of 8-bit bytes. The common language runtime uses Unicode UTF-16 (Unicode Transformation Format, 16-bit encoding form) to represent characters.

Applications that target the common language runtime use encoding to map character representations from the native character scheme to other schemes. Applications use decoding to map characters from non-native schemes to the native scheme. The following table lists the most commonly used classes in the System.Text namespace to encode and decode characters.

Character Scheme Class Explanation
ASCII encoding System.Text..::.ASCIIEncoding Converts to and from ASCII characters.
Multiple encoding System.Text..::.Encoding Converts characters to and from various encodings as specified in the Convert method.
UTF-16 Unicode encoding System.Text..::.UnicodeEncoding Converts to and from UTF-16 encoding. This scheme represents characters as 16-bit integers.
UTF-8 Unicode encoding System.Text..::.UTF8Encoding Converts to and from UTF-8 encoding. This variable-width encoding scheme represents characters using one to four bytes.

Базовые типы кодировки

Знаки — это абстрактные сущности, которые представляются с помощью множества различных схем знаков или кодовых страниц. Например, в кодировке Юникод UTF-16 знаки представляются в виде последовательности 16-битовых целых чисел, в то время как в кодировке Юникод UTF-8 те же самые знаки описываются в виде последовательности 8-битовых байт. Среда CLR использует для представления знаков кодировку Юникод UTF-16 (Unicode Transformation Format, 16-битовая кодировка).

Для отображения представления знаков из внутренней схемы знаков во внешние схемы приложения, ориентированные на среду CLR, используется кодирование. Для обратного преобразования знаков из внешних схем во внутренние схемы приложения используется декодирование. В следующей таблице перечислены классы из пространства имен System.Text, наиболее часто используемые для кодирования и декодирования знаков.

Схема знаков Класс Объяснение
Кодировка ASCII System.Text..::.ASCIIEncoding Преобразование в знаки ASCII и обратное преобразование.
Многоформатная кодировка System.Text..::.Encoding Преобразование знаков в различные форматы кодировки и обратное преобразование в порядке, определяемом методом Convert.
Кодировка Юникод UTF-16 System.Text..::.UnicodeEncoding Преобразование в формат UTF-16 и обратное преобразование. В этой схеме знаки представляются 16-битовыми целыми числами.
Кодировка Юникод UTF-8 System.Text..::.UTF8Encoding Преобразование в формат UTF-8 и обратное преобразование. В этой схеме с переменной длиной представления знаки представляются с использованием от одного до четырех байт.

The following code example converts a Unicode string into an array of bytes using the ASCIIEncoding..::.GetBytes method. Each byte in the array represents the ASCII value for the letter in that position of the string.

string MyString = "Encoding String."; ASCIIEncoding AE = new ASCIIEncoding(); byte[] ByteArray = AE.GetBytes(MyString); for(int x = 0;x <= ByteArray.Length - 1; x++) { Console.Write("{0} ", ByteArray[x]); }

This example displays the following to the console. The byte 69 is the ASCII value for the E character; the byte 110 is the ASCII value for the n character, and so on.

69 110 99 111 100 105 110 103 32 83 116 114 105 110 103 46

The following code example converts the preceding array of bytes into an array of characters using the ASCIIEncoding class. The GetChars method is used to decode the array of bytes.

ASCIIEncoding AE = new ASCIIEncoding(); byte[] ByteArray = { 69, 110, 99, 111, 100, 105, 110, 103, 32, 83, 116, 114, 105, 110, 103, 46 }; char[] CharArray = AE.GetChars(ByteArray); for(int x = 0;x <= CharArray.Length - 1; x++) { Console.Write(CharArray[x]); }

The preceding code displays the text Encoding String. to the console.

 


В следующем примере кода строка в формате Юникод преобразуется в байтовый массив с помощью метода ASCIIEncoding..::.GetBytes. Каждый байт массива представляет значение ASCII, соответствующее букве, находящейся в данном месте строки.

string MyString = "Encoding String."; ASCIIEncoding AE = new ASCIIEncoding(); byte[] ByteArray = AE.GetBytes(MyString); for(int x = 0;x <= ByteArray.Length - 1; x++) { Console.Write("{0} ", ByteArray[x]); }

Ниже показан консольный вывод этого примера. Байт 69 — это значение ASCII для знака E; байт 110 — это значение ASCII для знака n и т. д.

69 110 99 111 100 105 110 103 32 83 116 114 105 110 103 46

В следующем примере кода происходит преобразование полученного выше байтового массива в массив знаков с помощью класса ASCIIEncoding. Для декодирования байтового массива используется метод GetChars.

ASCIIEncoding AE = new ASCIIEncoding(); byte[] ByteArray = { 69, 110, 99, 111, 100, 105, 110, 103, 32, 83, 116, 114, 105, 110, 103, 46 }; char[] CharArray = AE.GetChars(ByteArray); for(int x = 0;x <= CharArray.Length - 1; x++) { Console.Write(CharArray[x]); }

Приведенный выше код выводит на консоль текст Encoding String.

 


Formatting Types

The.NET Framework provides a consistent, flexible, and comprehensive means for you to represent any of the numeric, enumeration, and date and time base data types as a string. Formatting is controlled by strings of format specifier characters that indicate how a base type value is to be represented. For example, format specifiers indicate whether a formatted number should be represented in scientific notation, or whether a formatted date should present the month as a number or a name.

The.NET Framework also uses cultural settings to represent a base type in a form appropriate to a particular culture. You can supply custom cultural settings, or use the default cultural setting associated with the current thread. For example, when formatting a currency type, the cultural setting specifies the characters to use for the currency symbol, group separator, and decimal separator.

The.NET Framework allows you to define custom formatting schemes and custom cultural settings. This ability enables you to expand the formatting schemes of existing base types to accommodate custom scenarios, or create custom formatting schemes for custom types.

Formatting Overview

The.NET Framework provides a customizable, general-purpose formatting mechanism to convert a value into a string suitable for display. For example, a numeric value can be formatted in hexadecimal, scientific notation, or a series of digits separated into groups with a user-specified punctuation mark. Dates and times can be formatted as appropriate for a particular country, region, or culture. An enumerated constant can be formatted as its numeric value or its name.

You control formatting by specifying a format string and format provider, or by using the defaults. A format string contains one or more format specifier characters that indicate how a value is to be converted. A format provider supplies additional control, replacement, and cultural information required to convert a specific type.

You can override the way the.NET Framework interprets a format string by implementing the IFormattable interface, provide your own format provider by implementing the IFormatProvider interface, and perform your own formatting by implementing the ICustomFormatter interface.

The.NET Framework provides a feature called composite formatting that uses one or more format strings to embed one or more formatted values in a result string. The result string can be used for further processing, displayed to the system console, or written to a stream.


Типы форматирования

Гибкие и удобные средства.NET Framework позволяют представлять числовые значения, перечисления, время и дату в виде строк. Форматирование задается строкой спецификатора формата, определяющего представление значения базового типа. Например, спецификаторы формата могут задавать научное представление числа или указывать, должен ли месяц быть представлен в формате даты числом или именем.

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

Платформа.NET Framework позволяет определять пользовательские схемы форматирования и региональные параметры. Таким образом можно расширить схемы форматирования существующих базовых типов для использования в пользовательских сценариях или создать пользовательские схемы форматирования для пользовательских типов.



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 104; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 18.221.165.246 (0.012 с.)