EN
C# / .NET - replace first 3 characters in string
0 points
In this article, we would like to show you how to replace the first 3 characters in a string in C# / .NET.
Quick solution:
xxxxxxxxxx
1
string text = "ABCD";
2
string replacement = "xyz";
3
string result = replacement + text.Substring(3);
4
5
Console.WriteLine(result); // xyzD
In this example, we will take the last 3
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
string text = "ABCD";
8
string replacement = "xyz";
9
string result = replacement + text.Substring(3);
10
11
Console.WriteLine(result); // xyzD
12
}
13
}
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
string text = "ABCD";
8
string replacement = "xyz";
9
string result = string.Concat(replacement, text.Substring(3));
10
11
Console.WriteLine(result); // xyzD
12
}
13
}
In this example, we use Regex.Replace()
with "^.{3}"
regex to replace the first 3 characters in the text
string.
Regex explanation:
^
- matches the beginning of the string,.
- matches any character except linebreaks,{3}
- 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
string text = "ABCD";
9
string replacement = "xyz";
10
string pattern = @"^.{3}";
11
string result = Regex.Replace(text, pattern, replacement);
12
13
Console.WriteLine(result); // xyzD
14
}
15
}
Note:
Regular expressions are slower than
Substring()
method.