EN
C# / .NET - replace first 3 characters in string (range operator .. )
0
points
In this article, we would like to show you how to replace the first 3 characters in a string in C# / .NET.
Note: range operator
..
was introduced in C# 8.0.
Quick solution:
string text = "ABCD";
string replacement = "xyz";
string result = replacement + text[3..];
Console.WriteLine(result); // xyzD
1. Practical examples
1.1 With +
and range operator
In this example, we will take the last 3
characters from the original string and add them to the end of the replacement.
using System;
public class StringUtils
{
public static void Main(string[] args)
{
string text = "ABCD";
string replacement = "xyz";
string result = replacement + text[3..];
Console.WriteLine(result); // xyzD
}
}
1.2 With string.Concat()
method and range operator
This approach is equivalent to the above one. Instead of +
operator we concatenate the strings using string.Concat()
method.
using System;
public class StringUtils
{
public static void Main(string[] args)
{
string text = "ABCD";
string replacement = "xyz";
string result = string.Concat(replacement, text[3..]);
Console.WriteLine(result); // xyzD
}
}
2. Practical example using string Regex.Replace()
with regex pattern
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.
).
using System;
using System.Text.RegularExpressions;
public class StringUtils
{
public static void Main(string[] args)
{
string text = "ABCD";
string replacement = "xyz";
string pattern = @"^.{3}";
string result = Regex.Replace(text, pattern, replacement);
Console.WriteLine(result); // xyzD
}
}
Note:
Regular expressions are slower than
Substring()
method.