Преобразование целого числа в строку в C#
В этом посте будет обсуждаться, как преобразовать целое число в строку в C#.
1. Использование Int32.ToString() метод
Простое и довольно эффективное решение состоит в том, чтобы вызвать ToString() метод для целочисленного экземпляра, чтобы преобразовать его в эквивалентное строковое представление.
2. Использование Convert.ToString() метод
The Convert.ToString() метод используется для преобразования указанного значения в его эквивалентное строковое представление.
3. Использование String.Format() метод
Мы можем использовать String.Format() метод для вставки целочисленного значения в другую строку, как показано ниже:
4. Интерполяция строк
Начиная с C# 6, можно использовать Строковая интерполяция ($), который обеспечивает удобный синтаксис для преобразования целого числа в строку.
5. Конкатенация с String.Empty() метод
Конкатенация строк в C# выполняется с помощью + оператор. Чтобы преобразовать целое число в строку, просто объедините целое число с пустой строкой.
6. Использование StringBuilder.Append() метод
The StringBuilder.Append() можно использовать для добавления строкового представления указанного целого числа к текущему экземпляру.
7. Использование String.Concat() метод
Мы можем использовать String.Concat() метод для создания строкового представления указанного целого числа.
8. Использование String.Join() метод
В следующем примере кода показано, как мы можем использовать String.Join() метод генерации строки из целого числа с использованием пустой строки в качестве разделителя.
Это все о преобразовании целого числа в строку в C#.
Оценить этот пост
Средний рейтинг 5 /5. Подсчет голосов: 21
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования
C# int to string conversion
C# int to String tutorial shows how to convert integers to strings. There are several ways to perform int to String conversion in C#. We can use string concatenation, string formatting, string building, and use built-in conversion methods.
Advertisements C# int to string conversion
is a type conversion or type casting, where an entity of integer data type is changed into string one.
In the examples of this tutorial, we build string messages that contains an integer.
C# int to string with Int32.ToString
The Int32.ToString method converts the numeric value to its equivalent string representation. The int.ToString is an alias for the Int32.ToString .
The example uses int.ToString to do int to string conversion.
Advertisements C# int to string with string concatenation
When we use the + operator on int and string parameters, the C# compiler internally performs type conversion.
The example uses string concatenation to do int to string conversion.
C# int to string with StringBuilder
StringBuilder represents a mutable string of characters. We can use StringBuilder to construct strings. We can append integers to the builder as well.
The code example uses StringBuilder to do int to string conversion.
Advertisements C# int to string other examples
The following example provides other ways to the int to string conversion in C#.
We use Convert.ToString , string.Format , and string interpolation to do int to string conversions.
In this article, we have shown how to perform int to string conversions in C#.
How to Convert an Int to a String in C++ – Integer Cast Tutorial
Ihechikara Vincent Abba

Type casting or type conversion is the process of converting a variable from one data type to another.
Type casting can be done implicitly or explicitly.
Implicit type casting gets done automatically via the compiler, while explicit type casting is done by the developer.
In this article, you’ll learn how to convert an integer to a string in C++ using the stringstream class and the to_string() method.
How to Convert an Int to a String in C++ Using the stringstream Class
Using the stringstream class, we can convert an integer to a string.
Here’s an example to help you understand why you’d need to convert an integer to a string:
In the example above, we created an int variable with a value of 20.
When we tried to concatenate that value in a string, we got an error saying «invalid operands of types. «.
The error was raised because we tried to perform an operation using two incompatible variable types. The solution would be to convert one variable and make it compatible with the other.
The stringstream class has insertion ( << ) and extraction ( >> ) operators.
The insertion operator is used to pass a variable to the stream. In our case, to pass an integer to the stream.
The extraction operator is used to give out the modified variable.
In other words, a stringstream object would take in a data type, convert it to another data type, and assign the new data type to a variable.
Here’s an example:
In the code above, we created a stringstream object called stream . Note that you must include the stringstream class before you can use it: include <sstream> .
We then inserted the integer into the stream: stream << age; .
After that, we created a new variable called age_as_string . This variable will store the string variable that will be extracted from the stream.
Lastly, we extracted the string type of the integer and stored it in the variable created above: stream >> age_as_string; .
Now we can concatenate the strings and get the desired result:
How to Convert an Int to a String in C++ Using the to_string() Method
You can use the to_string() method to convert int, float, and double data types to strings.
Here’s an example:
In the code above, we passed in the age variable to the to_string() : string age_as_string = to_string(age); .
This converted the age variable to a string. Just like the example in the last section, we can now use the variable as a string:
Summary
In this article, we talked about the different ways of converting an integer to a string in C++.
The examples showed how to use the stringstream class and the to_string() method to convert an integer to a string.
How to Convert int to string in C
The C library sprintf() function allows us to convert integers into a formatted string. In this example, we are going to make use of the sprintf() function from the C standard library. This function is just like a format specifier that takes the format in which we want to print the input.
Syntax
Parameters
- str: is a pointer to char str in which we will get output.
- formatspec : is used to specify the format which we want for output.
- arg1, arg2 are integers to convert into a string.
Return Value
If the conversion is successful It returns the length of converted to number to string else negative value is a return.
1.2 Program sprint() to convert int to string in C
In this C Program, we have taken a number input from the user and mystr is an empty buffer of type string. We are using the sprint function to convert the input number to a string. Finally, use the printf() function to print the output on the console.
Syntax
Parameters
- str = is a pointer to a char str in which we will get output.
- formatspec = is is used to specify the format which we want for output.
- arg1, arg2 are integers to convert into a string.
C Program to Convert an Integer to a String using sprintf()
2. Convert int to string in C Using itoa() function
The itoa() C function allows us to convert integer numbers into null-terminated strings. In this example, we are going to make use of the itoa() function. This function can be used by just including the header file in your program. This function accepts an integer and returns a null-terminated string.
Note:- This function is not a standard function and on the Linux Posix system it may not work. It will work on windows systems for sure.
Syntax
Parmeters
- val: The integer number need to convert into string.
- str : It is a character array and pointer to buffer in memory where null terminated result string will store.
- Base : The base is a numeric value range from 2 to 32 categories as below
- binary : if base is 2
- octal : if base is 8
- Decimal: if base is 10
- Hex : base is 16
2.1 Using itoa() function to convert int to string in C
In this example, we are using itoa() function to convert int to string. This function is not defined in ANSI-C. But some compilers support it.
C Program to Convert an Integer to a String in C by using itoa() Function
Summary
In this post we have learned how to convert int to string in C by using the following ways: