Languages
[Edit]
EN

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

0 points
Created by:
Nabila-Burnett
385

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

Quick solution:Ā 

int n = 2;
string originalString = "ABCD";

string replaced = originalString.Substring(0, originalString.Length - n) + "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)
    {
        int n = 2;
        string originalString = "ABCD";
        string newLetters = "12";

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

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

Output:

ABCD
AB12

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)
    {
        int n = 2;
        string originalString = "ABCD";
        string newLetters = "12";

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

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

Output:

ABCD
AB12

Ā References

  1. String Substring() - .NET Docs
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.
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