EN
C# / .NET - replace first n characters in string
0 points
In this article, we would like to show you how to replace the first n characters in a string in C# / .NET.
Quick solution:
xxxxxxxxxx
1
int n = 2;
2
string text = "ABCD";
3
string replacement = "xy";
4
string result = replacement + text.Substring(n);
5
6
Console.WriteLine(result); // xyCD
In this example, we will take the last n
characters from the original string and add them to the end of the replacement.
xxxxxxxxxx
1
using System;
2
3
public class StringUtils
4
{
5
public static void Main(string[] args)
6
{
7
int n = 2;
8
string text = "ABCD";
9
string replacement = "xy";
10
string result = replacement + text.Substring(n);
11
12
Console.WriteLine(result); // xyCD
13
}
14
}
This approach is equivalent to the above one. Instead of +
operator we concatenate the strings using string.Concat()
method.
xxxxxxxxxx
1
using System;
2
3
public class StringUtils
4
{
5
public static void Main(string[] args)
6
{
7
int n = 2;
8
string text = "ABCD";
9
string replacement = "xy";
10
string result = string.Concat(replacement, text.Substring(n));
11
12
Console.WriteLine(result); // xyCD
13
}
14
}
In this example, we use Regex.Replace()
with "^.{n}"
regex to replace the first 2 characters in the text
string.
Regex explanation:
^
- matches the beginning of the string,.
- matches any character except linebreaks,{n}
- matches the specified quantity of the previous token (in our case the.
).
xxxxxxxxxx
1
using System;
2
using System.Text.RegularExpressions;
3
4
public class StringUtils
5
{
6
public static void Main(string[] args)
7
{
8
int n = 2;
9
string text = "ABCD";
10
string replacement = "xy";
11
string pattern = @"^.{" + n + "}";
12
13
string result = Regex.Replace(text, pattern, replacement);
14
15
Console.WriteLine(result); // xyCD
16
}
17
}
Note:
Regular expressions are slower than
Substring()
method.