How to: Convert a string to an int 


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



ЗНАЕТЕ ЛИ ВЫ?

How to: Convert a string to an int



These examples show some different ways you can convert a string to an int. Such a conversion can be useful when obtaining numerical input from a command line argument, for example. Similar methods exist for converting strings to other numeric types, such as float or long. The table below lists some of those methods.

Numeric Type Method
decimal ToDecimal(String)
float ToSingle(String)
double ToDouble(String)
short ToInt16(String)
long ToInt64(String)
ushort ToUInt16(String)
uint ToUInt32(String)
ulong ToUInt64(String)

Example

This example calls the ToInt32(String) method to convert the string "29" to an int. It then adds 1 to the result and prints the output.

int i = Convert.ToInt32("29"); i++;   Console.WriteLine(i);
 

 


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

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

ß--

 

 

Пример

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

int i = Convert.ToInt32("29"); i++;   Console.WriteLine(i);
 

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

Преобразование шестнадцатеричных строк

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

Пример

Результатом следующего примера является шестнадцатеричное значение каждого символа в string. Сначала выполняется разбор string до массива символов. Затем для каждого символа вызывается метод ToInt32(Char) для получения его числового значения. В конце, формат номера меняется на шестнадцатеричный в string.

ß--


This example parses a string of hexadecimal values and outputs the character corresponding to each hexadecimal value. First it calls the Split(array<Char>[]()[]) method to obtain each hexadecimal value as an individual string in an array. Then it calls ToInt32(String, Int32) to convert the hexadecimal value to a decimal value represented as an int. It shows two different ways to obtain the character corresponding to that character code. The first technique uses ConvertFromUtf32(Int32) which returns the character corresponding to the integer argument as a string. The second technique explicitly casts the int to a char.

string hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21"; string[] hexValuesSplit = hexValues.Split(' '); foreach (String hex in hexValuesSplit) { // Convert the number expressed in base-16 to an integer. int value = Convert.ToInt32(hex, 16); // Get the character corresponding to the integral value. string stringValue = Char.ConvertFromUtf32(value); char charValue = (char)value; Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}", hex, value, stringValue, charValue); }
hexadecimal value = 48, int value = 72, char value = H or H hexadecimal value = 65, int value = 101, char value = e or e hexadecimal value = 6C, int value = 108, char value = l or l hexadecimal value = 6C, int value = 108, char value = l or l hexadecimal value = 6F, int value = 111, char value = o or o hexadecimal value = 20, int value = 32, char value = or hexadecimal value = 57, int value = 87, char value = W or W hexadecimal value = 6F, int value = 111, char value = o or o hexadecimal value = 72, int value = 114, char value = r or r hexadecimal value = 6C, int value = 108, char value = l or l hexadecimal value = 64, int value = 100, char value = d or d hexadecimal value = 21, int value = 33, char value =! or!

This example shows you another way to convert a hexadecimal string to an integer, by calling the Parse(String, NumberStyles) method.

string hexString = "8E2"; int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber); Console.WriteLine(num);  
 

Этот пример выполняет разбор string шестнадцатеричных значений и выводит символ, соответствующий каждому шестнадцатеричному значению. Сначала вызывается метод Split(array<Char>[]()[]) для получения каждого шестнадцатеричного значения как отдельной string в массиве. Затем вызывается метод ToInt32(String, Int32) для преобразования шестнадцатеричного значения в десятичное, представленное в формате int. В примере показано два разных способа получения символа, соответствующего этому коду символа. В первом случае используется ConvertFromUtf32(Int32), возвращающий символ, который соответствует целочисленному аргументу в виде string. По второму способу выполняется явное приведение int к char.

ß--

 

В следующем примере показан еще один способ преобразования шестнадцатеричной string в целое число путем вызова метода Parse(String, NumberStyles).

ß--


Arrays

An array is a data structure that contains several variables of the same type. Arrays are declared with a type:

type[] arrayName;

The following examples create single-dimensional, multidimensional, and jagged arrays:

class TestArraysClass { static void Main() { // Declare a single-dimensional array int[] array1 = new int[5]; // Declare and set array element values int[] array2 = new int[] { 1, 3, 5, 7, 9 }; // Alternative syntax int[] array3 = { 1, 2, 3, 4, 5, 6 }; // Declare a two dimensional array int[,] multiDimensionalArray1 = new int[2, 3]; // Declare and set array element values int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } }; // Declare a jagged array int[][] jaggedArray = new int[6][]; // Set the values of the first array in the jagged array structure jaggedArray[0] = new int[4] { 1, 2, 3, 4 }; } }

Array Overview

An array has the following properties:

· An array can be Single-Dimensional, Multidimensional or Jagged.

· The default value of numeric array elements are set to zero, and reference elements are set to null.

· A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.

· Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.

· Array elements can be of any type, including an array type.

· Array types are reference types derived from the abstract base type Array. Since this type implements IEnumerable and IEnumerable<(Of <(T>)>), you can use foreach iteration on all arrays in C#.


Массивы

Массив — это структура данных, содержащая несколько переменных одного типа. Массивы объявляются со следующим типом.

type[] arrayName;

В следующем примере показано создание одномерных, многомерных массивов и массивов массивов.

ß--

 

 

Общие сведения о массивах

Массив имеет следующие свойства.

· Массив может быть одномерным, многомерным или массивом массивов.

· Значение по умолчанию числовых элементов массива задано равным нулю, а элементы ссылок имеют значение NULL.

· Невыровненный массив является массивом массивов и поэтому его элементы являются ссылочными типами и инициализируются значением null.

· Индексация массивов начинается с нуля: массив с элементами n индексируется от 0 до n-1.

· Элементы массива могут быть любых типов, включая тип массива.

· Типы массива являются ссылочными типами, производными от абстрактного базового типа Array. Поскольку этот тип реализует IEnumerable и IEnumerable<(Of <(T>)>), в C# во всех массивах можно использовать итерацию foreach.


Arrays as Objects

In C#, arrays are actually objects, and not just addressable regions of contiguous memory as in C and C++. Array is the abstract base type of all array types. You can use the properties, and other class members, that Array has. An example of this would be using the Length property to get the length of an array. The following code assigns the length of the numbers array, which is 5, to a variable called lengthOfNumbers:

int[] numbers = { 1, 2, 3, 4, 5 }; int lengthOfNumbers = numbers.Length;

The System.Array class provides many other useful methods and properties for sorting, searching, and copying arrays.

Example

This example uses the Rank property to display the number of dimensions of an array.

class TestArraysClass { static void Main() { // Declare and initialize an array: int[,] theArray = new int[5, 10]; System.Console.WriteLine("The array has {0} dimensions.", theArray.Rank); } }

Output

The array has 2 dimensions.

 


Массивы как объекты

В языке C# массивы являются объектами, а не просто смежными адресуемыми областями памяти, как в C и C++. Array является абстрактным базовым типом для всех типов массивов. Можно использовать свойства и другие члены класса, которые имеет Array. В примере используется свойство Length для получения длины массива. В следующем коде длина массива numbers, равная 5, присваивается переменной lengthOfNumbers:

int[] numbers = { 1, 2, 3, 4, 5 }; int lengthOfNumbers = numbers.Length;

Класс System.Array позволяет использовать много других полезных методов и свойств для выполнения сортировки, поиска и копирования массивов.

Пример

В этом примере свойство Rank используется для отображения числа измерений массива.

class TestArraysClass { static void Main() { // Declare and initialize an array: int[,] theArray = new int[5, 10]; System.Console.WriteLine("The array has {0} dimensions.", theArray.Rank); } }

Результат

The array has 2 dimensions.

 


Single-Dimensional Arrays

You can declare an array of five integers as in the following example:

int[] array = new int[5];

This array contains the elements from array[0] to array[4]. The new operator is used to create the array and initialize the array elements to their default values. In this example, all the array elements are initialized to zero.

An array that stores string elements can be declared in the same way. For example:

string[] stringArray = new string[6];

Array Initialization

It is possible to initialize an array upon declaration, in which case, the rank specifier is not needed because it is already supplied by the number of elements in the initialization list. For example:

int[] array1 = new int[] { 1, 3, 5, 7, 9 };

A string array can be initialized in the same way. The following is a declaration of a string array where each array element is initialized by a name of a day:

string[] weekDays = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

When you initialize an array upon declaration, you can use the following shortcuts:

int[] array2 = { 1, 3, 5, 7, 9 }; string[] weekDays2 = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"

It is possible to declare an array variable without initialization, but you must use the new operator when you assign an array to this variable. For example:

int[] array3; array3 = new int[] { 1, 3, 5, 7, 9 }; // OK //array3 = {1, 3, 5, 7, 9}; // Error

C# 3.0 introduces implicitly typed arrays.



Поделиться:


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

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