1

I want to replace the character 'A' of the first character of a string if the first character is 0.

Data 01234500

Expected output A1234500

code

results getting - A12345AA


string formattedId = "01234500";
if(formattedId.Substring(0,1)=="0")
formattedId = formattedId.Replace("0","A");
Console.WriteLine(formattedId);
dotnetdev1
  • 33
  • 3

2 Answers2

2

The Replace() method always changes ALL instances of the targeted string. Instead, you can do this:

string formattedId = "01234500";

if(formattedId[0] == '0')
{
    formattedId = "A" + formattedId.Substring(1);
}
Console.WriteLine(formattedId);
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • formattedId[0] not working , its working for formattedId.Substring(0,1) – dotnetdev1 Feb 24 '23 at 17:24
  • 1
    @dotnetdev1 That's because `formattedId[0]` is only a character, not a string, which is why my answer has single quotes on the right-hand side of the equality expression. This will be significantly more efficient than the `StartsWith()` option. – Joel Coehoorn Feb 24 '23 at 17:45
0

You can use StartsWith() to check the first char and Substring(1) to get the part after first char:

string formattedId = "01234500";
if (formattedId?.StartsWith("0") is true)
{
    formattedId = "A" + formattedId.Substring(1);
}
Console.WriteLine(formattedId); // Output: A1234500
Ivan Vydrin
  • 273
  • 7