Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Concatenation of Strings in C#
3.
6 Effective Ways To Concatenate Strings In C#
4.
C# Concatenate Strings Using + Operator
4.1.
Example 1:
5.
C#
6.
String Interpolation in C#
6.1.
Example 2:
7.
C#
8.
String.Concatenate() in C#
8.1.
Example 3:
9.
C#
9.1.
Example 4:
10.
C#
11.
String.Join() in C#
11.1.
Example 5:
12.
C#
13.
String.Format() in C#
13.1.
Example 6: To insert a single object in a string.
14.
C#
14.1.
Example 7: To insert multiple objects in a string.
15.
C#
16.
StringBuilder.Append() in C#
16.1.
Example 8:
17.
C#
18.
Frequently Asked Questions
18.1.
How to add two strings together in C#?
18.2.
What is the best way to concat strings in C?
18.3.
Is string format quicker than C# concatenation?
18.4.
What is the difference between append and concat in C#?
19.
Conclusion
Last Updated: May 30, 2024
Medium

C# Concatenate Strings

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

In this article, we will discuss C# Concatenate Strings. We will look at six ways of C# Concatenate Strings and how to implement them.

c# concatenate strings

Concatenation of Strings in C#

String addition or concatenation, is a frequent operation in C# and .NET.

String.Concate(), String.Join(), String.Format(), StringBuilder.Append() and String Interpolation are all methods for adding, inserting, and merging strings provided by the String class.

String concatenation is adding or putting one at the end of another string. Strings are immutable in C# and .NET Core. Each operation creates a new string object even if you utilize the same string variable.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

6 Effective Ways To Concatenate Strings In C#

Here are six different ways to concatenate strings in C#.

  1. Use of + operator
  2. Use of String Interpolation
  3. Use of String.Concatenate() method
  4. Use of String.Join() method
  5. Use of String.Format() method
  6. Use of StringBuilder.Append() method
6 Effective Ways To Concatenate Strings In C#

Now let’s discuss these methods one by one.

Also read - C program to concatenate two strings

C# Concatenate Strings Using + Operator

The + or += operators are the simplest way to add two strings in C#.

Example 1 shows a code example that concatenates two strings and a special character.

Example 1:

  • C#

C#

using System;

class Example1 {
 static void Main() {
   // Simple string concatenation
   Console.WriteLine("Hello" + " " + "String " + "!");
   
   // Declare strings
   string fName = "Coding";
   string lName = "Ninjas";
  
   // Concatenate two string variables
   string name = fName + " " + lName;
   Console.WriteLine(name);

 }
}


Output 1:

Output1

Concatenation occurs at compile time for string literals and string constants; no concatenation occurs at run time. Concatenation of string variables happens only at run time.

String Interpolation in C#

String interpolation is a technique for joining variables as part of a string. String interpolation syntax begins with a '$' symbol, and code variables are enclosed in brackets.

The following code example concatenates strings to form a longer string.

Example 2:

  • C#

C#

using System;

class Example2 {
 static void Main() {
   // String Interpolation
   string city= "Mumbai";
   string country = "India";
   
   // Use string interpolation to concatenate strings.
   string cityOfcountry = $"{city} is a city in {country}.";
   Console.WriteLine(cityOfcountry);
 }
}


Output 2:

Output2

String.Concatenate() in C#

String.Concate() is a method that adds two strings, objects, and arrays of strings and string combinations. Let us see hoe to use it with an example.

Example 3:

  • C#

C#

using System;

class Example3 {
 static void Main() {
   // String.Concat method
   string String1 = "Coding";
   string String2 = "Ninjas";
   string finalString = string.Concat(String1, String2);
   
   Console.WriteLine(finalString);
 }
}


Output 3:

Output 3

We can also use the C# Concatenate String method “concat”, to add two concats together. The last line might seem intimidating initially, but it is easy to implement. Let us see how to do it.

Example 4:

  • C#

C#

using System;

class Example4{
 static void Main() {
   // String.Concat method
   string String1 = "Coding";
   string String2 = "Ninjas";
   
   string finalString = string.Concat(String1, String2);
   
   Console.WriteLine(finalString);
   
   // Concatenate Concat
   string doubleConcat = string.Concat(string.Concat(String1, String2), "Company");
   
   Console.WriteLine(doubleConcat);
 }
}


Output 4:

Output 4

String.Join() in C#

String.Join() concatenates array elements or collection members using the specified separator between each of the elements or members. The array or collection can contain any data, including numbers and objects. String.Join() can also concatenate string items of any data type with a range.

Let us see an example.

Example 5:

  • C#

C#

using System;

class Example5{
 static void Main() {
   // Using String.Join(String, String[])
   int[] inputArray = { 89, 78, 34, 76, 34, 21 };
   String sep = "; ";
   string finalresult = "Int: ";
   
   finalresult += String.Join(sep, inputArray);
   Console.WriteLine($"Result: {finalresult}");
 }
}


Output 5:

Output 5

String.Format() in C#

String.format() method formats strings by inserting objects and variables into other strings and literals with specified space and alignments. It is also frequently used to format strings into predefined formats.

String.Format() method has eight overloaded formats to provide options for formatting various objects and variables, including variables that can format strings. The eight overloaded methods are

  1. String.Format(String first, Object second) Method
  2. String.Format(String, params Object[]) Method
  3. String.Format(IFormatProvider, String, Object) Method 
  4. String.Format(IFormatProvider, String, Object, Object) Method  
  5. String.Format(IFormatProvider, String, Object, Object, Object) Method
  6. String.Format(IFormatProvider, String, Object[]) Method
  7. String.Format(String, Object, Object) Method
  8. String.Format(String, Object, Object, Object) Method

 

Example 6: To insert a single object in a string.

  • C#

C#

using System;  

namespace singleVariable { 
 class Example6 {
   public static void Main(string [] args) {

     int number = 8;
     // Format string
     string strFormat = String.Format("There are {0} mangoes in the basket.", number);
     Console.WriteLine(strFormat);
   }
 }
}


Output 6:

Output 6

Example 7: To insert multiple objects in a string.

  • C#

C#

using System;  

namespace multipleObject {
class Example7 {
public static void Main(string [] args) {

string name = "Rahul";
string programmingLanguage = "Csharp";

// Format the string
string strFormat = String.Format("{0} likes to code in {1}", name, programmingLanguage);
Console.WriteLine(strFormat);

Console.ReadLine();
}
}
}

Output 7:

Output 7

StringBuilder.Append() in C#

In .NET, string objects are immutable. 

What does this imply? 
It means that every time you use one of the String class methods, whether, with the same or a different variable, a new string object is created in memory. This means that memory space in your computer's memory is reserved for that new string. 

The more string manipulation methods you use, the more memory space is allocated in memory. That is, in a string manipulation-heavy code, if strings are not used wisely, they can cause serious app performance issues.

.NET provides the System.Text.StringBuilder class that allows you to modify strings without creating new ones. StringBuilder is highly recommended if your code contains more than a few hundred string concatenation operations. StringBuilder should not be used for some string concatenation operations. StringBuilder class is defined in the System.Text namespace. This namespace must be imported into your class or referenced directly in the object instantiation.

Let us understand this method of “C# Concatenate Strings” with the help of an example.

Example 8:

  • C#

C#

using System;
using System.Text;

class Example8 {

   // Main Method
   public static void Main()
   {
       // The capacity is 25
       StringBuilder sampleString = new StringBuilder("Welcome to ", 25);
        
       sampleString.Append("Coding Ninjas, ");
      
       sampleString.Append("Hello Everyone!");
       Console.WriteLine(sampleString);
   }
}


Output 8:

Output 8

 

Check out this article - C++ String Concatenation.

Frequently Asked Questions

How to add two strings together in C#?

To add two strings together in C#, you can use the + operator or the string.Concat() method. 

What is the best way to concat strings in C?

The best way to concatenate strings in C# is by using the StringBuilder class when dealing with large string manipulations. For smaller concatenations or simplicity, you can use the + operator or string.Concat().

Is string format quicker than C# concatenation?

Format (via Reflector) creates a StringBuilder and then calls AppendFormat on it. As a result, it is faster than concate for multiple strings.

What is the difference between append and concat in C#?

The difference between append and concat in C#, append is for efficiently building large strings using StringBuilder, avoiding many intermediate objects. On the other hand, concat in C# is for joining multiple strings into one, creating a new string object with string.Concat().

Conclusion

This blog discusses different ways to concatenate strings in C#. As we discussed a total of 6 methods: using + operator, using interpolation, using format(), join(), concatenate() methods, and using StringBuilder.Append() method. We looked at an example for each for clarity of concepts. Toward the end, we looked at some frequently asked questions on this topic. We hope that you got a clear understanding of C# Concatenate Strings.
Check out this problem - Longest String Chain

To explore more interesting coding-related articles refer to the following links:

Also check out the Interview guide for Product Based Companies as well as some of the Popular interview problems from top tech companies like Amazon, Adobe, Google, Uber, Microsoft, etc.

Refer to our guided pathways on Code studio to learn more about Competitive ProgrammingJavaScriptSystem DesignDSA C++etc. Enroll in our courses, and use the accessible sample exams and questions as a guide. For placement preparations, look at the interview experiences and interview package.

Happy Coding!

Live masterclass