Languages
[Edit]
EN

C#/.NET - replace last char in string

3 points
Created by:
Kate_C
2878

In C#/.NET it is possible to replace last char in string in few ways.

1. string.Substring example

string text = "abc";
string to = "D";

string result = text.Substring(0, text.Length - 1) + to;

Console.WriteLine(result);

Output:

abD

2. Regex.Replace example

string text = "abc";
string to = "D";

Regex expression = new Regex(".$");
string result = expression.Replace(text, to);

Console.WriteLine(result);

Output:

abD

3. References

  1. String.Substring - Microsoft Docs
  2. Regex - Microsoft Docs
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.