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