In this source code example, we show you different ways to concatenate string in C# with an example.
Immutable strings can be added using the + operator or the Concat method. They form a new string which is a chain of all concatenated strings. Mutable strings have the Append method which builds a string from any number of other strings.
C# String Concatenation Example
The example creates five sentences by concatenating strings.
using System;
using System.Text;
class Example {
static void Main() {
string s1 = "Source";
string s2 = " Code ";
string s3 = "Examples";
// concatenate string using + operator
Console.WriteLine(s1 + s2 + s3);
// concatenate string using Concat method
Console.WriteLine(string.Concat(string.Concat(s1, s2), s3));
var sb = new StringBuilder();
sb.Append(s1);
sb.Append(s2);
sb.Append(s3);
Console.WriteLine(sb);
Console.WriteLine("{0}{1}{2}", s1, s2, s3);
Console.WriteLine($"{s1}{s2}{s3}");
}
}
Output:
Source Code Examples
Source Code Examples
Source Code Examples
Source Code Examples
Source Code Examples
A new string is formed by using the + operator:
// concatenate string using + operator
Console.WriteLine(s1 + s2 + s3);
The Concat method concatenates two strings. The method is a static method of the System.String class.
// concatenate string using Concat method
Console.WriteLine(string.Concat(string.Concat(s1, s2), s3));
A mutable object of the StringBuilder type is created by calling the Append method three times:
var sb = new StringBuilder();
sb.Append(s1);
sb.Append(s2);
sb.Append(s3);
Console.WriteLine(sb);
A string is formed with string formatting:
Console.WriteLine("{0}{1}{2}", s1, s2, s3);
Finally, the strings are added with the interpolation syntax:
Console.WriteLine($"{s1}{s2}{s3}");
Comments
Post a Comment