Как в c преобразовать string в int

How to convert string to int in C#?

Here you will learn how to convert a numeric string to the integer type.

In C#, you can convert a string representation of a number to an integer using the following ways:

  1. Parse() method
  2. Convert class
  3. TryParse() method — Recommended

Parse Method

The Parse() methods are available for all the primitive datatypes. It is the easiest way to convert from string to integer.

The Parse methods are available for 16, 32, 64 bit signed integer types:

  • Int16.Parse()
  • Int32.Parse()
  • Int64.Parse()

It takes up to 3 parameters, a string which is mandatory to convert string to integer format, the second parameter contains the number style which specifies the style of the number to be represented, and the third parameter represents string cultural-specific format.

The following example demonstrates converting numeric strings to integers.

As you can see in the above example, a valid numeric string can be converted to an integer. The Parse() method allows conversion of the numeric string into different formats into an integer using the NumberStyles enum e.g string with parentheses, culture-specific numeric string, with a currency symbol, etc.

However, the passed string must be a valid numeric string or in the range of the type on which they are being called. The following statements throw exceptions.

  • Converts valid numeric string to integer value.
  • Supports different number styles.
  • Supports culture-specific custom formats.
  • Input string must be a valid numeric string.
  • The numeric string must be within the range of int type on which the method is called.
  • Throws exception on converting null or invalid numeric string.

Convert Class

Another way to convert string to integer is by using static Convert class. The Convert class includes different methods which convert base data type to another base data type.

The Convert class includes the following methods to convert from different data types to int type.

  • Convert.ToInt16()
  • Convert.ToInt32()
  • Convert.ToInt64()

The Convert.ToInt16() method returns the 16-bit integer e.g. short, the Convert.ToInt32() returns 32-bit integers e.g. int and the Convert.ToInt64() returns the 64-bit integer e.g. long.

  • Converts from any data type to integer.
  • Converts null to 0, so not throwing an exception.
  • Input string must be valid number string, cannot include different numeric formats. Only works with valid integer string.
  • Input string must be within the range of called IntXX method e.g. Int16, Int32, Int64.
  • The input string cannot include parenthesis, comma, etc.
  • Must use a different method for different integer ranges e.g. cannot use the Convert.ToInt16() for the integer string higher than «32767».

Visit Convert class for more information.

TryParse Method

The TryParse() methods are available for all the primitive types to convert string to the calling data type. It is the recommended way to convert string to an integer.

The TryParse() method converts the string representation of a number to its 16, 32, and 64-bit signed integer equivalent. It returns boolean which indicates whether the conversion succeeded or failed and so it never throws exceptions.

The TryParse() methods are available for all the integer types:

  • Int16.TryParse()
  • Int32.TryParse()
  • Int64.TryParse()

The TryParse() method takes 3 parameters identical to the Parse() method having the same functionality.

The following example demonstrates the TryParse() method.

The following example demonstrates converting invalid numeric string.

In the above example, numberStr = «123456as» which is invalid numeric string. However, Int32.TryParse() method will return false instead of throwing an exception.

Thus, the TryParse() method is the safest way to converting numeric string to integer type when we don’t know whether the string is a valid numeric string or not.

Преобразование строки в целое число в 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#.

Оценить этот пост

Средний рейтинг 5 /5. Подсчет голосов: 27

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования ��

Как перевести из string в int?

Как перевести тип данных из string[] в int?
как перевести тип данных из string в int?

Как int перевести в string?
Товарисчи, приветствую всех. Помогите, пожалуйста, написать красивую, не слишком длинную функцию.

Как перевести string в int?
Как перевести из string в int. Прочитал строку из файла по символьно.

C# how to convert a string to int

Time for a new post in my how-to series. In this series, I try to provide updated answers for common .NET/C# questions. I found that when googling common terms like «convert string to int», «write to a file», and similar, I would often get outdated StackOverflow answers, showing how to solve each problem with .NET 2 or even older. Even worse, most examples lack key aspects like exception handling and bad practices. For today’s post, I will show you the best ways of converting strings to integers in C#.

C# how to convert a string to int

You have already tried converting a string to an int. Like parsing input from a text box in a system that didn’t have modern model binding as we are used to today or when converting the output from a third-party API. While working for multiple companies both as a permanent and as a freelancer, I’ve seen a thousand lines of code, converting between data types. The most common pattern I’ve seen in C# is using the Parse -method:

While Parse provides a nice and simple interface for converting strings to int, it’s rarely the right method to use. What happens if you provide something else than a number to the Parse -method:

As expected, the Parse -method throws a FormatException. I cannot count the times I’ve seen this construct:

Even documentation shows this approach as a valid way to parse ints. So, why is this a poor solution? Using exceptions as a control flow reduces the performance and makes your code harder to read. Luckily, .NET provides a much better way to parse ints without the need to catch exceptions: the TryParse -method:

TryParse returns a boolean indicating if the parameter ( s ) was successfully parsed or not. If parsed, the value will go into the out parameter ( i ). Parsing with a default value on an invalid string is still dead simple:

Convert.ToInt32

There’s a Convert class in the System namespace that you may be aquainted with. Convert offers a range of methods for converting one data type to another. For converting strings to ints, it’s an abstraction on top of the Parse method from the previous section. This means that you will need to catch the FormatException to use the ToInt32 -method:

While it might be nice with a common abstraction for converting data types, I tend not to use the Convert class. Being forced to control flow using exceptions is something I always try to avoid, which (to my knowledge) isn’t possible with the Convert class. Besides this, there are some additional things that you will need to be aware of when using the ToInt32 -method. Take a look at the following code:

In the code, I’m converting the char 1 to an integer and writing it to the console. What do you expect the program to produce? The number 1 , right? That’s not the case, though. The overload of the ToInt32 -method accepting a char as a parameter, converts the char to its UTF code, in this case 49 . I’ve seen this go down a couple of times.

To summarize my opinion about the Convert -class in terms of converting strings to integers, stick to the TryParse -method instead.

Exception handling

As long as you use the TryParse -method, there’s no need to catch any exceptions. Both the Parse and the ToInt32 -method requires you to deal with exceptions:

Parsing complex strings

From my time working with financial systems, I was made aware of an overload of the TryParse -method that I don’t see a lot of people using. The overload looks like this:

The parameter that I want to introduce you to is NumberStyles enum. The parameter accepts a bitwise combination of flags, allowing for more complex strings to be successfully parsed as integers. It’s often much more readable to use this TryParse -overload, rather than doing a range of manipulations on the input string before parsing (like removing thousand separators, whitespaces, currency signs, etc.). Let’s look at a couple of examples:

AllowParantheses will accept parantheses in the input string. But be aware that a parenthesized string is converted to a negative value. This format is often used in accounting and financial systems.

AllowCurrencySymbol will accept currency symbols inside the input string.

AllowThousands will accept a thousand separator in the input string.

Like any bitwise flag, multiple NumberStyles can be combined:

Parsing anti-patterns

When looking at code, I often see different anti-patterns implemented around int parsing. Maybe someone copies code snippets from StackOverflow or blog posts with unnecessary code, who knows. This section is my attempt to debunk common myths.

Trimming for whitespace

This is probably the most common code example I’ve seen:

By calling Trim the developer makes sure not to parse a string with whitespaces in the start and/or end. Trimming strings isn’t nessecary, though. The TryParse -method automatically trims the input string.

Not using the TryParse overload

Another common anti-pattern is to do manual string manipulation to a string before sending it to the TryParse -method. Examples I’ve seen is to remove thousand separators, currency symbols, etc.:

Like we’ve already seen, calling the TryParse -overload with the AllowThousands flag (or one of the others depending in the input string) is a better and more readable solution.

Control flow with exceptions

We already discussed this. But since this is a section of anti-patterns I want to repeat it. Control flow with exceptions slow down your code and make it less readable:

As I already mentioned, using the TryParse -method is a better solution here.

Avoid out parameters

There’s a bit of a predicament when using the TryParse -method. Static code analysis tools often advise against using out parameters. I don’t disagree there. out parameters allows for returning multiple values from a method which can violate the single responsibility principle. Whether you want to use the TryParse -method probably depends on how strict you want to be concerning the single responsibility principle.

If you want to, you can avoid the out parameter (or at least only use it once) by creating a small extension method:

The method uses the built-in tuple support available in C# 7.

Convert to an array

A question that I often see is the option of parsing a list of integers in a string and converting it to an array or list of integers. With the knowledge already gained from this post, converting a string to an int array can be done easily with a bit of LINQ:

By splitting without parameters we get an enumerable of individual characters that can be converted to integers.

In most cases you would get a comma-separated list or similar. Parsing and converting that will require some arguments for the Split method:

By splitting the string on comma ( , ) we get the individual characters in between.

When working with external APIs, developers come up with all sorts of weird constructs for representing null or other non-integer values. To make sure that you only parse integers, use the Char.IsNumber helper:

By only including characters which are numbers, we filter values like null from the input string.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *