-2

I have an invoice number. I would like to replace the 3rd last character with a dot (.)

Example:

XA260153758i01

I would like to replace the small i with dot (.):

XA260153758.01

Now, the small i could be anything, So I do not know what character will be in the 3rd last postion, I only know that the 3rd last character should always be replaced with a dot (.)

How to script that ?

Sinatr
  • 20,892
  • 15
  • 90
  • 319
  • 1
    None of the answers to the duplicate question are actually optimal if you're replacing a *single* character. Cid's answer below would be more suitable. – Matthew Watson Oct 14 '20 at 08:11
  • 1
    Or you can do it in a one-liner like this (assuming your string is called `s`): `s = new string(s.Select((c, i) => i == s.Length - 3 ? '.' : c).ToArray());` – Matthew Watson Oct 14 '20 at 08:36

1 Answers1

1

You can use the class StringBuilder, it's pretty nice to manipulate strings easily :

// using System.Text;

var input = new StringBuilder("XA260153758i01");
    
// TODO : Check for the length to avoid ArgumentOutOfRangeException (negative indexes)
input[input.Length - 3] = '.';
    
Console.WriteLine(input.ToString()); // output is XA260153758.01
Cid
  • 14,968
  • 4
  • 30
  • 45