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:
string originalString = "ABCDE";
string replaced = originalString.Substring(0, originalString.Length - 3) + "123";
Console.WriteLine(originalString); // ABCDE
Console.WriteLine(replaced); // AB123
Practical examples
1. Using Substring()
method
using System;
public class Program
{
static string ReplaceLastLetters(string text, int letterCount, string newLetters)
{
string substring = text.Substring(0, text.Length - letterCount); // ABCDE -> AB
return substring + newLetters;
}
public static void Main(string[] args)
{
string originalString = "ABCDE";
string newLetters = "123";
string replaced = ReplaceLastLetters(originalString, 3, newLetters);
Console.WriteLine(originalString); // ABCDE
Console.WriteLine(replaced); // AB123
}
}
Output:
ABCDE
AB123
1. Using Remove()
method
using System;
public class Program
{
static string ReplaceLastLetters(string text, int letterCount, string newLetters)
{
string substring = text.Remove(text.Length - letterCount, letterCount); // ABCDE -> AB
return substring + newLetters;
}
public static void Main(string[] args)
{
string originalString = "ABCDE";
string newLetters = "123";
string replaced = ReplaceLastLetters(originalString, 3, newLetters);
Console.WriteLine(originalString); // ABCDE
Console.WriteLine(replaced); // AB123
}
}
Output:
ABCDE
AB123