Languages
[Edit]
EN

C# / .NET - replace last character in string

0 points
Created by:
Veer-Ahmad
487

In this article, we would like to show you how to replace the last character in string in Java.

Quick solution: 

string originalString = "123";

string replaced = originalString.Substring(0, originalString.Length - 1) + "4";

Console.WriteLine(originalString); // 123
Console.WriteLine(replaced);       // 124

 

Practical examples

1. Using Substring() method

using System;

public class Program
{
    static string ReplaceLastLetter(string text, string newLetter)
    {
        string substring = text.Substring(0, text.Length - 1); // ABC -> AB
        return substring + newLetter; // ABD
    }

    public static void Main(string[] args)
    {
        string text = "ABC";
        string newLetter = "D";

        string replaced = ReplaceLastLetter(text, newLetter);

        Console.WriteLine(text);     // ABC
        Console.WriteLine(replaced); // ABD
    }
}

Output:

ABC
ABD

1. Using Remove() method

using System;

public class Program
{
    static string ReplaceLastLetter(string originalString, string newLetter)
    {
        string substring = originalString.Remove(originalString.Length - 1, 1); // ABC -> AB
        return substring + newLetter; // ABD
    }

    public static void Main(string[] args)
    {
        string originalString = "ABC";
        string newLetter = "D";

        string replaced = ReplaceLastLetter(originalString, newLetter);

        Console.WriteLine(originalString); // ABC
        Console.WriteLine(replaced);       // ABD
    }
}

Note:

Duplicated article: C#/.NET - replace last char in string

In the future, combine these 2 articles into one.

References

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - replace last char in string

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join