Append a char to end of a string in C#
This post will discuss how to append a char to the end of a string in C#.
1. Using + operator
A simple solution to append a character to the end of a string is using the + operator. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; public class Example { public static void Main() { String s = "ab"; s = s + 'c'; Console.WriteLine(s); // abc } } |
Alternatively, you can concatenate a character to the end of a string with the += operator.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; public class Example { public static void Main() { String s = "ab"; s += 'c'; Console.WriteLine(s); // abc } } |
Finally, to concatenate a character at the front of a string, do as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<pre class="lang:c# decode:true">using System; public class Example { public static void Main() { String s = "bc"; s = 'a' + s; Console.WriteLine(s); // abc } } |
2. Using StringBuilder
If you need to append a character multiple times to a string, consider using a StringBuilder. The idea is to convert the String object to StringBuilder, and use its Append() method to append each character to it. Finally, invoke the ToString() method to convert the StringBuilder back into a string. Note that the StringBuilder class is available under the System.Text namespace.
|
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() { String s = "ab"; StringBuilder sb = new StringBuilder(s); sb.Append('c'); sb.Append('d'); s = sb.ToString(); Console.WriteLine(s); // abcd } } |
3. Using String.Insert() method
If you need to insert another string at a specified position in the given string, you can use the String.Insert() method. This method only accepts a string, and it is not overloaded for the character data type.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; public class Example { public static void Main() { String s = "ab"; s = s.Insert(s.Length, "c"); Console.WriteLine(s); // abc } } |
That’s all about appending a char to the end of a 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 :)