How can I change the first two characters of a string to "01" with C#?

Take a look at Substring and string.Format.

string result = string.Format("01{0}", abc.Substring(2));

or Regex.Replace

string result = Regex.Replace(abc, "^00", "01");

You can use Substring().

var res = "01" + abc.Substring(2);

Edit Some performance consideration when more replacements to be done.

You can use StringBuilder if you have more sub strings to replace, read this article How to improve string concatenation performance in Visual C#

String Concatenation VS String Builder

One technique to improve string concatenation over strcat() in Visual C/C++ is to allocate a large character array as a buffer and copy string data into the buffer. In the .NET Framework, a string is immutable; it cannot be modified in place. The C# + concatenation operator builds a new string and causes reduced performance when it concatenates large amounts of text.

However, the .NET Framework includes a StringBuilder class that is optimized for string concatenation. It provides the same benefits as using a character array in C/C++, as well as automatically growing the buffer size (if needed) and tracking the length for you. The sample application in this article demonstrates the use of the StringBuilder class and compares the performance to concatenation. Reference

Changing "002776766" with "012776766" using StringBuilder.

StringBuilder sb = new StringBuilder(def);
sb[1] = '1';    
def = sb.ToString();

Tags:

C#