C# String Concatenation
String concatenation is the process of combining two or more strings to form a single string. This can be done using the +
operator, the String.Concat()
method, or the StringBuilder
class for efficient concatenation in loops.
Key Topics
1. Using the +
Operator
Example: Concatenation with +
Operator
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName); // Outputs: John Doe
2. Using String.Concat()
Example: Concatenation with String.Concat()
string part1 = "Hello";
string part2 = "World";
string message = String.Concat(part1, " ", part2);
Console.WriteLine(message); // Outputs: Hello World
3. Using StringBuilder
The StringBuilder
class is efficient for concatenating large numbers of strings, especially within loops.
Example: Concatenation with StringBuilder
using System.Text;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 5; i++)
{
sb.Append("Number ");
sb.Append(i);
sb.Append("\n");
}
Console.WriteLine(sb.ToString());
Key Takeaways
- Use
+
for simple concatenations. String.Concat()
can concatenate multiple strings efficiently.StringBuilder
is recommended for concatenations in loops.