Languages
[Edit]
EN

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

0 points
Created by:
Nabila-Burnett
265

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

Quick solution:

string text = "ABC";
string replacement = "12";
string result = text[0..^2] + replacement;

Console.WriteLine(result);  // A12

 

Practical example

In this example, we use the range operator .., which is an alternative to Substring() method to removing the last 2 characters from the text string, then we add the replacement at their place.

using System;

public class StringUtils
{
    public static void Main(string[] args)
    {
        string text = "ABC";
        string replacement = "12";
        string result = text[0..^2] + replacement;

        Console.WriteLine("Original string: " + text);     // ABC
        Console.WriteLine("Modified string: " + result);   // A12
    }
}

Output:

Original string: ABC
Modified string: A12

Note:

The replacement length doesn't have to be equal to 2. You can remove the last 2 characters from the end of the string and add any number of characters instead. 

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