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