user1679941
user1679941

Reputation:

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

I have strings like this:

var abc = "00345667";
var def = "002776766";

The first two characters are always "00". How can I change these to "01" ?

Upvotes: 11

Views: 30147

Answers (8)

overcomer
overcomer

Reputation: 2374

If you are using C# 8 or above, you can also do it with a range operator. It's very readable

var res = "01" + abc[2..];

Upvotes: 2

Anirudha
Anirudha

Reputation: 32807

You can do that with Regex.Replace() which can be found in the namespace System.Text.RegularExpressions.

abc = Regex.Replace(abc ,"^00","01");
                        |      
                        |
                        |->^ depicts that start of the string

Upvotes: 3

Andrew
Andrew

Reputation: 1120

Use String Interpolation

var abc = "00345667";
var abc = $"01{abc.Substring(2)}";

Upvotes: 0

Buddhika De Silva
Buddhika De Silva

Reputation: 59

var abc = "00345667";
var def = "002776766";
string str= string.Format("01{0}", abc.TrimStart('00'));

Upvotes: 1

Adil
Adil

Reputation: 148150

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

Upvotes: 19

Kevin M
Kevin M

Reputation: 5506

you can use the function Replace in Regex.

like   var abc = "00345667";

       var newvar =Regex.Replace(abc, "^00", "01");     

Upvotes: 0

Sergey Metlov
Sergey Metlov

Reputation: 26311

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

Upvotes: 9

Tilak
Tilak

Reputation: 30718

Try this

"00".Concat(abc.Substring(2));
"00".Concat(def.Substring(2));

Upvotes: 0

Related Questions