- Преобразование строки в целое число в C#
- 1. Использование Int32.Parse() метод
- 2. Использование Int32.TryParse() метод
- 3. Использование Convert.ToInt32() метод
- Си шарп int parse
- Convert
- How to Convert a String to an Integer in C# – with Code Examples
- How to Convert a String to an Int Using Int32.Parse()
- How to Convert a String to an Int Using Convert.ToInt32()
- How to Convert a String to an Int Using Int32.TryParse()
- Conclusion
- How to convert a string to a number (C# Programming Guide)
- Call Parse or TryParse methods
- Call Convert methods
- Feedback
Преобразование строки в целое число в C#
В этом посте мы обсудим, как преобразовать строку в эквивалентное целочисленное представление в C#.
1. Использование Int32.Parse() метод
Чтобы преобразовать строковое представление числа в эквивалентное ему 32-разрядное целое число со знаком, используйте метод Int32.Parse() метод.
The Int32.Parse() метод выдает FormatException если строка не числовая. Мы можем справиться с этим с помощью блока try-catch.
2. Использование Int32.TryParse() метод
Лучшей альтернативой является вызов Int32.TryParse() метод. Он не генерирует исключение, если преобразование завершается неудачно. Если преобразование не удалось, этот метод просто возвращает false.
3. Использование Convert.ToInt32() метод
The Convert.ToInt32 можно использовать для преобразования указанного значения в 32-разрядное целое число со знаком.
Этот метод выдает FormatException если строка не числовая. Это можно решить с помощью блока try-catch.
Это все о преобразовании строки в целое число в C#.
Средний рейтинг 4.81 /5. Подсчет голосов: 32
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂
Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно
Си шарп int parse
Все примитивные типы имеют два метода, которые позволяют преобразовать строку к данному типу. Это методы Parse() и TryParse() .
Метод Parse() в качестве параметра принимает строку и возвращает объект текущего типа. Например:
int a = int.Parse("10"); double b = double.Parse("23,56"); decimal c = decimal.Parse("12,45"); byte d = byte.Parse("4"); Console.WriteLine($"a= b= c= d=");
Стоит отметить, что парсинг дробных чисел зависит от настроек текущей культуры. В частности, для получения числа double я передаю строку «23,56» с запятой в качестве разделителя. Если бы я передал точку вместо запятой, то приложение выдало ошибку выполнения. На компьютерах с другой локалью, наоборот, использование запятой вместо точки выдало бы ошибку.
Чтобы не зависеть от культурных различий мы можем установить четкий формат с помощью класса NumberFormatInfo и его свойства NumberDecimalSeparator :
using System.Globalization; IFormatProvider formatter = new NumberFormatInfo < NumberDecimalSeparator = "." >; double number = double.Parse("23.56", formatter); Console.WriteLine(number); // 23,56
В данном случае в качестве разделителя устанавливается точка. Однако тем не менее потенциально при использовании метода Parse мы можем столкнуться с ошибкой, например, при передачи алфавитных символов вместо числовых. И в этом случае более удачным выбором будет применение метода TryParse() . Он пытается преобразовать строку к типу и, если преобразование прошло успешно, то возвращает true . Иначе возвращается false:
Console.WriteLine("Введите строку:"); string? input = Console.ReadLine(); bool result = int.TryParse(input, out var number); if (result == true) Console.WriteLine($"Преобразование прошло успешно. Число: "); else Console.WriteLine("Преобразование завершилось неудачно");
Если преобразование пройдет неудачно, то исключения никакого не будет выброшено, просто метод TryParse возвратит false, а переменная number будет содержать значение по умолчанию.
Convert
Класс Convert представляет еще один способ для преобразования значений. Для этого в нем определены следующие статические методы:
- ToBoolean(value)
- ToByte(value)
- ToChar(value)
- ToDateTime(value)
- ToDecimal(value)
- ToDouble(value)
- ToInt16(value)
- ToInt32(value)
- ToInt64(value)
- ToSByte(value)
- ToSingle(value)
- ToUInt16(value)
- ToUInt32(value)
- ToUInt64(value)
В качестве параметра в эти методы может передаваться значение различных примитивных типов, необязательно строки:
int n = Convert.ToInt32("23"); bool b = true; double d = Convert.ToDouble(b); Console.WriteLine($"n= d=");
Однако опять же, как и в случае с методом Parse, если методу не удастся преобразовать значение к нужному типу, то он выбрасывает исключение FormatException.
How to Convert a String to an Integer in C# – with Code Examples
Edeh Israel Chidera
There are various situations where you need to convert a string to a number. Whether you are working with user input or data from an external source, converting a string to a number is a common task for developers.
This article will explore some of the most common methods to convert a string to an integer in C# using the int.Parse() , int.TryParse() , and Convert.ToInt32() methods.
This article will also provide examples to help you understand the syntax of each method. Whether you are a beginner or an experienced programmer, this guide will provide a user-friendly introduction to the topic.
The Int keyword is an alias for the System.Int32 type, and it is utilized for declaring variables that can hold 32-bit signed integers within the range of -2,147,483,648 to 2,147,483,647. Int32 is a built-in value type that represents a 32-bit signed integer. You can convert a string to an Int using the following method.
How to Convert a String to an Int Using Int32.Parse()
Int32.Parse() is the easiest way to convert a string to an integer. It takes a string as a parameter. Here is an example:
string numberString = “8”; int i = int.Parse(numberString); Console.WriteLine("Value of i: ", i);
The above code shows how to convert a string to an Integer using the int.Parse() method. The method takes a string variable called numberString and converts it to an int.
The downside of using the int.Parse() method is that an exception will be thrown if it cannot be successfully parsed to an integer. To avoid this issue, you can use a try-catch block while using int.Parse() . Here is how to do this:
string numString = "12"; try < int num = int.Parse(numString); >catch(FormatException ex)
Another possible solution is using TryParse() , which we’ll discuss below.
How to Convert a String to an Int Using Convert.ToInt32()
Convert.ToInt32() is a static method provided by C# to convert a string to a 32-bit signed integer. This method takes a string variable as input and returns an integer. Here is an example:
string numString = "123"; int num = Convert.ToInt32(numString);
In the code block above, we have declared a string variable, numString , and assigned it a value. We then use the Convert.ToInt32() method to convert this string to an integer and assign it to a variable named num .
The Convert.ToInt32() method has two exceptions, FormatException and OverflowException and is able to convert a null variable to 0 without throwing an exception.
How to Convert a String to an Int Using Int32.TryParse()
Compared to the int.Parse() method, int.TryParse() is a safer way to convert a string to a 32-bit signed integer.
This method takes in a string variable and an out parameter and returns a bool of value true if the parsing is successful. The result of the parsing is stored in an out parameter.
This is the safest way of converting a string variable to an Integer. Here is an example:
string numString = "12"; if (int.TryParse(numString, out int num)) < // Conversion successful, do something with num. Console.WriteLine("Successful"); Console.WriteLine(num); >else < // Conversion failed, handle the error. Console.WriteLine("Unsuccessful.."); >
In the above code, we tried to parse a string variable called numString to an integer using the int.TryParse() method. The result is stored in the num variable if the conversion is successful. If the conversion fails, the success variable is set to false and the num variable is assigned its default value.
Conclusion
Converting a string to a number is a common task in programming, and C# provides various ways to accomplish this task.
In this article, we saw some of the methods to convert a string to an integer in C# using the Parse() , TryParse() , and Convert() methods. I hope this article helped you learn more about converting strings to ints in C#.
How to convert a string to a number (C# Programming Guide)
You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System.Convert class.
It’s slightly more efficient and straightforward to call a TryParse method (for example, int.TryParse(«11», out number) ) or Parse method (for example, var number = int.Parse(«11») ). Using a Convert method is more useful for general objects that implement IConvertible.
You use Parse or TryParse methods on the numeric type you expect the string contains, such as the System.Int32 type. The Convert.ToInt32 method uses Parse internally. The Parse method returns the converted number; the TryParse method returns a boolean value that indicates whether the conversion succeeded, and returns the converted number in an out parameter. If the string isn’t in a valid format, Parse throws an exception, but TryParse returns false . When calling a Parse method, you should always use exception handling to catch a FormatException when the parse operation fails.
Call Parse or TryParse methods
The Parse and TryParse methods ignore white space at the beginning and at the end of the string, but all other characters must be characters that form the appropriate numeric type ( int , long , ulong , float , decimal , and so on). Any white space within the string that forms the number causes an error. For example, you can use decimal.TryParse to parse «10», «10.3», or » 10 «, but you can’t use this method to parse 10 from «10X», «1 0» (note the embedded space), «10 .3» (note the embedded space), «10e1» ( float.TryParse works here), and so on. A string whose value is null or String.Empty fails to parse successfully. You can check for a null or empty string before attempting to parse it by calling the String.IsNullOrEmpty method.
The following example demonstrates both successful and unsuccessful calls to Parse and TryParse .
using System; public static class StringConversion < public static void Main() < string input = String.Empty; try < int result = Int32.Parse(input); Console.WriteLine(result); >catch (FormatException) < Console.WriteLine($"Unable to parse ''"); > // Output: Unable to parse '' try < int numVal = Int32.Parse("-105"); Console.WriteLine(numVal); >catch (FormatException e) < Console.WriteLine(e.Message); >// Output: -105 if (Int32.TryParse("-105", out int j)) < Console.WriteLine(j); >else < Console.WriteLine("String could not be parsed."); >// Output: -105 try < int m = Int32.Parse("abc"); >catch (FormatException e) < Console.WriteLine(e.Message); >// Output: Input string was not in a correct format. const string inputString = "abc"; if (Int32.TryParse(inputString, out int numValue)) < Console.WriteLine(numValue); >else < Console.WriteLine($"Int32.TryParse could not parse '' to an int."); > // Output: Int32.TryParse could not parse 'abc' to an int. > >
The following example illustrates one approach to parsing a string expected to include leading numeric characters (including hexadecimal characters) and trailing non-numeric characters. It assigns valid characters from the beginning of a string to a new string before calling the TryParse method. Because the strings to be parsed contain a few characters, the example calls the String.Concat method to assign valid characters to a new string. For a larger string, the StringBuilder class can be used instead.
using System; public static class StringConversion < public static void Main() < var str = " 10FFxxx"; string numericString = string.Empty; foreach (var c in str) < // Check for numeric characters (hex in this case) or leading or trailing spaces. if ((c >= '0' && c = 'A' && char.ToUpperInvariant(c) else < break; >> if (int.TryParse(numericString, System.Globalization.NumberStyles.HexNumber, null, out int i)) < Console.WriteLine($"'' --> '' --> "); > // Output: ' 10FFxxx' --> ' 10FF' --> 4351 str = " -10FFXXX"; numericString = ""; foreach (char c in str) < // Check for numeric characters (0-9), a negative sign, or leading or trailing spaces. if ((c >= '0' && c else < break; >> if (int.TryParse(numericString, out int j)) < Console.WriteLine($"'' --> '' --> "); > // Output: ' -10FFXXX' --> ' -10' --> -10 > >
Call Convert methods
The following table lists some of the methods from the Convert class that you can use to convert a string to a number.
Numeric type | Method |
---|---|
decimal | ToDecimal(String) |
float | ToSingle(String) |
double | ToDouble(String) |
short | ToInt16(String) |
int | ToInt32(String) |
long | ToInt64(String) |
ushort | ToUInt16(String) |
uint | ToUInt32(String) |
ulong | ToUInt64(String) |
The following example calls the Convert.ToInt32(String) method to convert an input string to an int. The example catches the two most common exceptions that can be thrown by this method, FormatException and OverflowException. If the resulting number can be incremented without exceeding Int32.MaxValue, the example adds 1 to the result and displays the output.
using System; public class ConvertStringExample1 < static void Main(string[] args) < int numVal = -1; bool repeat = true; while (repeat) < Console.Write("Enter a number between −2,147,483,648 and +2,147,483,647 (inclusive): "); string? input = Console.ReadLine(); // ToInt32 can throw FormatException or OverflowException. try < numVal = Convert.ToInt32(input); if (numVal < Int32.MaxValue) < Console.WriteLine("The new value is ", ++numVal); > else < Console.WriteLine("numVal cannot be incremented beyond its current value"); >> catch (FormatException) < Console.WriteLine("Input string is not a sequence of digits."); >catch (OverflowException) < Console.WriteLine("The number cannot fit in an Int32."); >Console.Write("Go again? Y/N: "); string? go = Console.ReadLine(); if (go?.ToUpper() != "Y") < repeat = false; >> > > // Sample Output: // Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive): 473 // The new value is 474 // Go again? Y/N: y // Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive): 2147483647 // numVal cannot be incremented beyond its current value // Go again? Y/N: y // Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive): -1000 // The new value is -999 // Go again? Y/N: n
Feedback
Submit and view feedback for