how to replace only first character of a string in C#

Advertisements

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);

>Solution :

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

string formattedId = "01234500";
if (input.StartsWith("0"))
{
    input = "A" + input.Substring(1);
}
Console.WriteLine(input); // Output: A1234500

Leave a Reply Cancel reply