Reputation:
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
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
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
Reputation: 59
var abc = "00345667";
var def = "002776766";
string str= string.Format("01{0}", abc.TrimStart('00'));
Upvotes: 1
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
Reputation: 5506
you can use the function Replace in Regex.
like var abc = "00345667";
var newvar =Regex.Replace(abc, "^00", "01");
Upvotes: 0
Reputation: 26311
Take a look at Substring and string.Format.
string result = string.Format("01{0}", abc.Substring(2));
string result = Regex.Replace(abc, "^00", "01");
Upvotes: 9
Reputation: 30718
Try this
"00".Concat(abc.Substring(2));
"00".Concat(def.Substring(2));
Upvotes: 0