EN
C# / .NET - add character to string
0 points
In this article, we would like to show you how to add character to string in C#.
Quick solution:
xxxxxxxxxx
1
string text = "ABC";
2
char character = 'x';
3
string result = text + character;
4
5
Console.WriteLine(result); // ABCDx
or:
xxxxxxxxxx
1
string text = "ABCD";
2
char character = 'x';
3
int index = 1;
4
5
string result = text.Insert(index, character.ToString());
6
7
Console.WriteLine(result); // AxBCD
In this example, we add a character at the end of the text
string using +
operator.
xxxxxxxxxx
1
using System;
2
3
public class TestClass
4
{
5
public static void Main()
6
{
7
string text = "ABC";
8
char character = 'x';
9
string result = text + character;
10
11
Console.WriteLine(result);
12
}
13
}
Output:
xxxxxxxxxx
1
ABCDx
In this example, we use Insert()
method to add a character to the string at specific position (index).
xxxxxxxxxx
1
using System;
2
3
public class TestClass
4
{
5
public static void Main()
6
{
7
string text = "ABCD";
8
char character = 'x';
9
int index = 1;
10
11
string result = text.Insert(index, character.ToString());
12
13
Console.WriteLine(result);
14
}
15
}
Output:
xxxxxxxxxx
1
AxBCD