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