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