EN
C# / .NET - replace part of string from given index
0 points
In this article, we would like to show you how to replace part of string from given index in C#.
Quick solution:
xxxxxxxxxx
1
string text = "ABCD";
2
string replacement = "xy";
3
4
int position = 1;
5
int numberOfCharacters = 2;
6
7
string result = text.Remove(position, numberOfCharacters).Insert(position, replacement);
8
9
Console.WriteLine(result); // Output: AxyD
In this example, we use Remove()
and Insert()
methods to replace part of string from given position (index).
xxxxxxxxxx
1
using System;
2
3
public class TestClass
4
{
5
public static void Main()
6
{
7
string text = "ABCD";
8
string replacement = "xy";
9
10
int position = 1; // start at index 1
11
int numberOfCharacters = 2; // number of characters to replace
12
13
string result = text.Remove(position, numberOfCharacters).Insert(position, replacement);
14
15
Console.WriteLine(result); // Output: AxyD
16
}
17
}
Output:
xxxxxxxxxx
1
AxyD
In this example, we present how to replace part of string from given index using StringBuilder
.
xxxxxxxxxx
1
using System;
2
using System.Text;
3
4
public class TestClass
5
{
6
public static void Main()
7
{
8
string text = "ABCD";
9
string replacement = "xy";
10
11
int position = 1; // start at index 1
12
int numberOfCharacters = 2; // number of characters to replace
13
14
var stringBuilder = new StringBuilder(text);
15
16
stringBuilder.Remove(position, numberOfCharacters);
17
stringBuilder.Insert(position, replacement);
18
19
text = stringBuilder.ToString();
20
21
Console.WriteLine(text);
22
}
23
}
Output:
xxxxxxxxxx
1
AxyD