I am developing web application using C#. I want to replace multiple character in a string. For example,
string str = "abc_def|ghij_klmn:opq|rst:uv_wx|yz";
str = str.Replace("_","-");
str = str.Replace("|",", ");
str = str.Replace(":",". ");
OR
string str = "abc_def|ghij_klmn:opq|rst:uv_wx|yz";
str = str.Replace("_","-").Replace("|",", ").Replace(":",". ");
The above are the sample coding, actually I want to replace more characters. Is there any performance related issue in above two codes?
This may be a duplicate question, I searched for that, but I didn't find...
Thanks
The two examples you provided are the same as each other.
Now, string replacing in general depends entirely on your use case. For example, this won't be a big performance hit:
string str = "abc_def|ghij_klmn:opq|rst:uv_wx|yz";
str = str.Replace("_","-").Replace("|",", ").Replace(":",". ");
...but this will be:
for (var i = 0; i < 100000; i++) {
string str = "abc_def|ghij_klmn:opq|rst:uv_wx|yz";
str = str.Replace("_","-").Replace("|",", ").Replace(":",". ");
}
If the latter type of operation is what you're after, I would suggest using a StringBuilder, since it will modify its internal structures directly (instead of immutable strings):
var sb = new StringBuilder(str);
...and chain Replace calls from there.
Alternatively, if that still doesn't provide you with the perf you require you can always look into unsafe code.. but that takes a whole different level of energy and understanding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With