Languages
[Edit]
EN

C# / .NET - replace last 2 characters in string

0 points
Created by:
martineau
300

In this article, we would like to show you how to replace the last 2 characters in a string in C#.

Quick solution: 

string originalString = "ABCD";

string replaced = originalString.Substring(0, originalString.Length - 2) + "12";

Console.WriteLine(originalString); // ABCD
Console.WriteLine(replaced);       // AB12

 

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); // ABCD -> AB
        return substring + newLetters;
    }

    public static void Main(string[] args)
    {
        string originalString = "ABCD";
        string newLetters = "12";

        string replaced = ReplaceLastLetters(originalString, 2, newLetters);

        Console.WriteLine(originalString); // ABCD
        Console.WriteLine(replaced);       // AB12
    }
}

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); // ABCD -> AB
        return substring + newLetters;
    }

    public static void Main(string[] args)
    {
        string originalString = "ABCD";
        string newLetters = "12";

        string replaced = ReplaceLastLetters(originalString, 2, newLetters);

        Console.WriteLine(originalString); // ABCD
        Console.WriteLine(replaced);       // AB12
    }
}

Output:

ABCD
AB12

 References

  1. String Substring() - .NET Docs

C# / .NET - String (popular problems)

C# / .NET - replace last 2 characters 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