Concatenate multiple integers to get a new string in C#
This article illustrates the different techniques to concatenate multiple integers to get a new string in C#.
1. Using Concatenation Operator
A simple solution to concatenate multiple integers together to get a string is using the String.Concat() method. This is the preferred method over the string concatenation operator +, which can join only string instances and requires casting to concatenate integers.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { int i = 100; int j = 10; string s = String.Concat(i, j); Console.WriteLine(s); // 10010 } } |
2. Using String.Format() method
Alternatively, you can use the String.Format() method to concatenate multiple integers in C#. To illustrate, consider the following code, which joins two integers.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { int i = 100; int j = 10; string s = string.Format("{0}{1}", i, j); Console.WriteLine(s); // 10010 } } |
3. Using String Interpolation
The String interpolation ($) provides a convenient syntax for concatenating multiple values together to form a string. This is available since C# 6 and can be used as follows to concatenate two integers.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { int i = 100; int j = 10; string s = $"{i}{j}"; Console.WriteLine(s); // 10010 } } |
4. Using StringBuilder
The StringBuilder class is recommended for concatenating multiple values together in C#, as it outperforms all other methods. It has the Append() method, which is overloaded to accept any data type.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Text; public class Example { public static void Main() { int i = 100; int j = 10; string s = new StringBuilder() .Append(i) .Append(j) .ToString(); Console.WriteLine(s); // 10010 } } |
That’s all about concatenating multiple integers to get a new string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)