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

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

formattedId[0] not working , its working for formattedId.Substring(0,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.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.