Как перевести строку в число c

от admin

Преобразование строки в целое число в 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 и многие другие популярные языки программирования.

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

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#.

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.:

Читать:
Html как сделать проверку пароля c

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.

Как перевести строку в число c

Нередко в программах встречается ситуация, когда надо преобразовать число в строку или строку в число. Для этой цели в стандартной библиотеке языка С определены функции strtol() и snprintf() .

Из строки в число. strtol

Функция strtol() преобразует строку в число типа long int . Функция определена в заголовочном файле stdlib.h и имеет следующий прототип:

str — строка с числом, которое надо преобразовать в числовой тип. Ключевое слово restrict указывает компилятору оптимизировать код и что никакой другой параметр не будет указывать на адрес данного параметра.

str_end — указатель на последний символ строки. Данный параметр можно игнорировать, передавая ему значение NULL

base — основание, система исчисления, в которую надо преобразовать данные (значение от 2 до 36).

Результатом функции является преобразованное число типа long .

Например, преобразуем строку в число в десятичной системе:

В примере выше второй параметр функции никак не использовался — мы ему передавали значение NULL , и функция нормально работала. Однако он может быть полезен, если нам надо получить остаток строки, которая идет после числа:

Из числа в строку. snprintf

Функция snprintf() преобразует число в отформатированную строку. Функция определена в заголовочном файле stdio.h и имеет следующий прототип:

str_buffer — строка, в которую помещается преобразованное число.

buffer_size — максимальное количество символов строки. Функция записывает в строку buffer-size — 1 байт и добавляет концевой нулевой байт

format — задает формат преобразования в строку.

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

Как перевести строку в число c

Converting a string to int is one of the most frequently encountered task in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we can convert numbers that are stored as strings.

Example:

There are 5 significant methods to convert strings to numbers in C++ as follows:

  1. Using stoi() function
  2. Using atoi() function
  3. Using stringstream
  4. Using sscanf() function
  5. Using for Loop

1. String to int Conversion Using stoi() Function

The stoi() function in C++ takes a string as an argument and returns its value in integer form. This approach is popular in current versions of C++, as it was first introduced in C++11.

If you observe stoi() a little closer you will find out that it stands for:

stoi() function with example and meaning

Breakdown of stoi() in simple terms

Syntax:

Parameters:

  • str: string to be converted. (compulsory)
  • position: starting position. (optional with default value = 0)
  • base: base of the number system. (optional with default value = 10)

Example:

As we can see, stoi() method supports both C++ style and C style strings.

We can also use atoi() function for performing this task.

2. String to int Conversion Using atoi()

The atoi() function in C++ takes a character array or string literal as an argument and returns its value in an integer. It is defined in the <stdlib.h> header file. This function is inherited by C++ from C language so it only works on C style strings i.e. array of characters.

If you observe atoi() a little closer you will find out that it stands for:

Breakdown of atoi() in simple terms

Breakdown of atoi() in simple terms

Example:

stoi() vs atoi()

4. Syntax:

4. Syntax:

int atoi (const char * str);

3. String to int Conversion Using stringstream Class

The stringstream class in C++ allows us to associate a string to be read as if it were a stream. We can use it to easily convert strings of digits into ints, floats, or doubles. The stringstream class is defined inside the <sstream> header file.

It works similar to other input and output streams in C++. We first create a stringstream object as shown below:

Syntax:

Then insert a numeric string into it using the ( << ) insertion operator.

Example:

At last, we extract the numeric value from the stream using the ( >> ) extraction operator.

Example:

The below C++ program demonstrates how to convert a string to int using a stringstream object:

Похожие статьи