Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading