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

Преобразование строки в значение типа "int"

В следующих примерах показано как преобразовать строку в значение типа int. Такое преобразование можно использовать, к примеру, при получении числовых входных данных из аргументов командной строки. Существуют аналогичные методы преобразования строк в другие числовые типы, такие как float и long. В следующей таблице перечислены некоторые из этих методов класса Convert.

--

Пример

В данном примере вызывается метод ToInt32(String) класса Convert для преобразования строки "29" в значение типа int. Затем к результату добавляется 1, а выходные данные печатаются.

int i = Convert.ToInt32("29");

i++;

Console.WriteLine(i);

30

Another way of converting a string to an int is through the Parse or TryParse methods of the System..::.Int32 struct. The ToUInt32 method uses Parse internally. If the string is not in a valid format, Parse throws an exception whereas TryParse does not throw an exception but returns false. The examples below demonstrate both successful and unsuccessful calls to Parse and TryParse.

int i = Int32.Parse("-105");

Console.WriteLine(i);

-105

int j;

Int32.TryParse("-105", out j);

Console.WriteLine(j);

-105

try

{

int m = Int32.Parse("abc");

}

catch (FormatException e)

{

Console.WriteLine(e.Message);

}

Input string was not in a correct format.

string s = "abc";

int k;

bool parsed = Int32.TryParse(s, out k);

if (!parsed)

Console.WriteLine("Int32.TryParse could not parse '{0}' to an int.\n", s);

Int32.TryParse could not parse 'abc' to an int.

Также можно преобразовать значение типа string в значение типа int с помощью методов Parse или TryParse структуры System..::.Int32. Метод ToUInt32 использует Parse внутри себя. Если строка имеет недопустимый формат, метод Parse создает исключение, а метод TryParse не создает исключение, но возвращает значение "false". В приведенных ниже примерах демонстрируются успешные и неуспешные вызовы методов Parse и TryParse.

--

How to: Convert Hexadecimal Strings

These examples show you how to convert to and from hexadecimal strings. The first example shows you how to obtain the hexadecimal value of each character in a string. The second example parses a string of hexadecimal values and outputs the character corresponding to each hexadecimal value. The third example demonstrates an alternative way to parse a hexadecimal string value to an integer.

Example

This example outputs the hexadecimal value of each character in a string. First it parses the string to an array of characters. Then it calls ToInt32(Char) on each character to obtain its numeric value. Finally, it formats the number as its hexadecimal representation in a string.

string input = "Hello World!";

char[] values = input.ToCharArray();

foreach (char c in values)

{

// Get the integral value of the character.

int value = Convert.ToInt32(c);

// Convert the decimal value to a hexadecimal value in string form.

string hex = String.Format("{0:X}", value);

Console.WriteLine("Hexadecimal value of {0} is {1}", c, hex);

}

Hexadecimal value of H is 48

Hexadecimal value of e is 65

Hexadecimal value of l is 6C

Hexadecimal value of l is 6C

Hexadecimal value of o is 6F

Hexadecimal value of is 20

Hexadecimal value of W is 57

Hexadecimal value of o is 6F

Hexadecimal value of r is 72

Hexadecimal value of l is 6C

Hexadecimal value of d is 64

Hexadecimal value of ! is 21