Languages
[Edit]
EN

C# / .NET - replace the last 4 characters in a string

0 points
Created by:
Dirask Admin - Marwin
1430

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

Quick solution: 

string originalString = "abcdefg";

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

Console.WriteLine(originalString); // abcdefg
Console.WriteLine(replaced);       // abc1234

 

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

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

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

        Console.WriteLine(originalString); // abcdefg
        Console.WriteLine(replaced);       // abc1234
    }
}

Output:

abcdefg
abc1234

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

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

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

        Console.WriteLine(originalString); // abcdefg
        Console.WriteLine(replaced);       // abc1234
    }
}

Output:

abcdefg
abc1234

 References

  1. String Substring() - .NET Docs

C# / .NET - String (popular problems)

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