Easy Way to Concatenate Letters Into a String
Adding strings is a common operation in C# and .NET. The String class provides several ways to add, insert, and merge strings including + operator, String.Concate(), String.Join(), String.Format(), StringBuilder.Append(), and String Interpolation.
Concatenating strings is appending or inserting one string to the end of another string. Strings in C# and .NET Core are immutable. That means, even if you use same string variable, after every operation, a new string object is created.
Adding strings is a common operation in C# and .NET. The String class provides several ways to add, insert, and merge strings including + operator, String.Concate(), String.Join(), String.Format(), StringBuilder.Append(), and String Interpolation. The code examples demonstrate various methods to concatenate strings, insert string, append string, and merge strings using C# String class and its methods.
Here are the 6 ways to concatenate strings in C#.
- Using + operator
- String Interpolation
- String.Concatenate() method
- String.Join() method
- String.Format() method
- StringBuilder.Append() method
1. Concatenate String Using + Operator
The simplest method of adding two strings in C# is using + or += operators.
The following code example in Listing 1 concatenates two strings and a special character.
// Simple string concatenation Console.WriteLine("Hello" + " " + "String " + "!");
The following code example concatenates two string variables.
// Declare strings string firstName = "Mahesh"; string lastName = "Chand"; // Concatenate two string variables string name = firstName + " " + lastName; Console.WriteLine(name);
Listing 1.
Result of Listing 1 is displayed in Figure 1.
Figure 1.
Note: For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
2. String Interpolation in C#
String interpolation is a method to concatenate variables as a part of a string. Syntax of string interpolation starts with a '$' symbol and code variables are within a bracket {}.
The following code example in Listing 2 concatenates strings to create a longer string.
// String Interpolation string author = "Mahesh Chand"; string book = "C# Programming"; // Use string interpolation to concatenate strings. string bookAuthor = $"{author} is the author of {book}."; Console.WriteLine(bookAuthor);
Listing 2.
3. Concatenate string using String.Concate method in C#
String.Concate() method concatenates two strings, two objects, and two arrays of strings and combinations of them.
The following code example in Listing 3 concats two strings.
// String.Concat method string fName = "Mahesh"; string lName = "Chand"; string Name = string.Concat(fName, lName);
Listing 3.
The following code example in Listing 4 concats a Concat inside a Concat.
// Concatenate Concat string Name3 = string.Concat(string.Concat(fName, lName), "Beniwal");
Listing 4.
The following code example in Listing 5 concats four strings into a single string.
// Concatenate an array of strings string[] authors = { "Mahesh Chand ", "Chris Love ", "Dave McCarter ", "Praveen Kumar "}; // Concatenate all strings of an array into one string string arrayStr = string.Concat(authors); Console.WriteLine(arrayStr);
Listing 5.
The following code example in Listing 6 concats a string with an array of strings into a single string.
// Concatenate a string and an array of strings string strArrStr = string.Concat("Authors: ", authors); Console.WriteLine(strArrStr);
Listing 6.
4. Concatenate string using String.Join method
String.Join() method concatenates the elements of an array or the members of a collection, using the specified separator between each element or member. The array or the collection can be any data type including numbers and objects. String.Join method also allows you to concatenate string items of any data types with a range.
The following code example in Listing 7 concatenates an array of int values to a string separated by a comma and space.
// Using String.Join(String, String[]) int[] intArray = { 1, 3, 5, 7, 9 }; String seperator = ", "; string result = "Int, "; result += String.Join(seperator, intArray); Console.WriteLine($"Result: {result}");
Listing 7.
The following code example in Listing 8 concatenates an array element separated by a separator. The second and third parameters of String.Join method specified the starting index of the array to start joining the number of elements in the array.
// Using String.Join(String, String[], int int) // Let's concatenate first two strings of the array String[] arr2 = { "Mahesh Chand ", "Chris Love ", "Dave McCarter ", "Praveen Kumar " }; String seperator2 = ", "; string result2 = "First Author, "; result2 += String.Join(seperator2, arr2, 1, 2); Console.WriteLine($"Result: {result2}");
Listing 8.
5. Concatenate string using String.Format method in C#
String.Format() method formats strings in a desired format by inserting objects and variables with specified space and alignments into another strings and literals. It is also often used to format strings into specific formats.
String.Format() method has 8 overloaded formats to provide options to format various objects and variables that allow various variables to format strings.
Note: In C# 6 or later versions, String Interpolation is recommended. Sting interpolation is more flexible and more readable and can achieve the same results without composite formatting.
Insert a single object in a string
We can insert one or more objects and expressions in a string at a specified position using the String.Format method. The position in the string starts at the 0th index.
For single object formatting, the first argument is the format and the second argument is the value of the object. The object is replaced at the {0} position in the string.
public static string Format (string format, object arg0);
The following code example in Listing 9 inserts a DateTime object in an existing string format.
/* *** Simple String.Format **/ string date = String.Format("Today's date is {0}", DateTime.Now); Console.WriteLine(date);
Listing 9.
As you can see from the above code example, {0} is at the last portion in the string and the second argument is a DateTime.Now. In this case, string portion {0} will be replaced by the value of DateTime.Now in the string. Figure 2 is the result of the above code.
Figure 2.
Insert multiple objects in a string
We can insert multiple objects or expressions in a string to give it a desired format. The following code example in Listing 10 creates a string by inserting 5 objects.
/* *** String.Format with multiple objects **/ string author = "Mahesh Chand"; string book = "Graphics Programming with GDI+"; int year = 2003; decimal price = 49.95m; string publisher = "APress"; // Book details string bookDetails = String.Format("{0} is the author of book {1} \n " + "published by {2} in year {3}. \n Book price is ${4}. ", author, book, publisher, year, price); Console.WriteLine(bookDetails);
Listing 10.
As you can see from the above code example, the String.Format has placeholders for objects, starting at 0th to 4th index. The {0} is replaced by the first object passed in the method, {1} is replaced by the second object passed in the method and so on.
The output of Listing 10 generates Figure 3.
Figure 3.
6. StringBuilder.Append method in C#
String object in .NET is immutable. What does that mean? It means every time you use one of the String class methods, no matter if you use the same variable or a new variable, a new string object is created in memory. That means, a memory space is allocated for that new string in your computer memory. The more string methods you use to manipulate strings, the more memory space will be allocated in memory. That means in a string manipulation heavy code, if strings are not used wisely, it could lead to some serious app performance issues.
.NET provides the System.Text.StringBuilder class that can be used to modify strings without creating new string objects. StringBuilder is highly recommended if you have more than a few hundred string concatenation operations in your code. StringBuilder is not recommended for a few string concatenation operations.
StringBuilder class is defined in the System.Text namespace. You must either import this namespace in your class or reference is direct in the object instantiation.
using System.Text;
StringBuilder constructor can take a string or can be no arguments.
The following code snippet creates a StringBuilder and appends 3 strings.
System.Text.StringBuilder builder = new System.Text.StringBuilder("Mahesh Chand"); builder.Append(", "); builder.Append("Chris Love"); builder.Append(", Praveen Kumar");
The following code example creates a string of numbers from 0 to 999 and each number is separated by a comma and a space.
System.Text.StringBuilder numbers = new System.Text.StringBuilder(); // Create a string of 1000 numbers from 0 to 999 // separated by a comma and space for (int counter = 0; counter <= 999; counter++) { numbers.Append(counter); numbers.Append(", "); } Console.WriteLine(numbers);
The output of the above code looks like Figure 4.
Figure 4.
Summary
C# and .NET provide various options to concatenate strings. In the code examples listed in this article, we saw how to use these options to concatenate strings.
Continue reading more, Most Common C# String Code Examples.
Source: https://www.c-sharpcorner.com/article/6-effective-ways-to-concatenate-strings-in-c-sharp-and-net-core/