EN
C# / .NET - replace last 3 characters in string
0 points
In this article, we would like to show you how to replace the last 3 characters in a string in C#.
Quick solution:
xxxxxxxxxx
1
string originalString = "ABCDE";
2
3
string replaced = originalString.Substring(0, originalString.Length - 3) + "123";
4
5
Console.WriteLine(originalString); // ABCDE
6
Console.WriteLine(replaced); // AB123
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
static string ReplaceLastLetters(string text, int letterCount, string newLetters)
6
{
7
string substring = text.Substring(0, text.Length - letterCount); // ABCDE -> AB
8
return substring + newLetters;
9
}
10
11
public static void Main(string[] args)
12
{
13
string originalString = "ABCDE";
14
string newLetters = "123";
15
16
string replaced = ReplaceLastLetters(originalString, 3, newLetters);
17
18
Console.WriteLine(originalString); // ABCDE
19
Console.WriteLine(replaced); // AB123
20
}
21
}
Output:
xxxxxxxxxx
1
ABCDE
2
AB123
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
static string ReplaceLastLetters(string text, int letterCount, string newLetters)
6
{
7
string substring = text.Remove(text.Length - letterCount, letterCount); // ABCDE -> AB
8
return substring + newLetters;
9
}
10
11
public static void Main(string[] args)
12
{
13
string originalString = "ABCDE";
14
string newLetters = "123";
15
16
string replaced = ReplaceLastLetters(originalString, 3, newLetters);
17
18
Console.WriteLine(originalString); // ABCDE
19
Console.WriteLine(replaced); // AB123
20
}
21
}
Output:
xxxxxxxxxx
1
ABCDE
2
AB123