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