EN
C# / .NET - replace last character in string
0 points
In this article, we would like to show you how to replace the last character in string in Java.
Quick solution:
xxxxxxxxxx
1
string originalString = "123";
2
3
string replaced = originalString.Substring(0, originalString.Length - 1) + "4";
4
5
Console.WriteLine(originalString); // 123
6
Console.WriteLine(replaced); // 124
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
static string ReplaceLastLetter(string text, string newLetter)
6
{
7
string substring = text.Substring(0, text.Length - 1); // ABC -> AB
8
return substring + newLetter; // ABD
9
}
10
11
public static void Main(string[] args)
12
{
13
string text = "ABC";
14
string newLetter = "D";
15
16
string replaced = ReplaceLastLetter(text, newLetter);
17
18
Console.WriteLine(text); // ABC
19
Console.WriteLine(replaced); // ABD
20
}
21
}
Output:
xxxxxxxxxx
1
ABC
2
ABD
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
static string ReplaceLastLetter(string originalString, string newLetter)
6
{
7
string substring = originalString.Remove(originalString.Length - 1, 1); // ABC -> AB
8
return substring + newLetter; // ABD
9
}
10
11
public static void Main(string[] args)
12
{
13
string originalString = "ABC";
14
string newLetter = "D";
15
16
string replaced = ReplaceLastLetter(originalString, newLetter);
17
18
Console.WriteLine(originalString); // ABC
19
Console.WriteLine(replaced); // ABD
20
}
21
}
Note:
Duplicated article: C#/.NET - replace last char in string
In the future, combine these 2 articles into one.