I just wondered what the easiest way to replace string characters that should later be replaced.
For example:
var str = "[Hello World]"; //enclose all occurences of [ and ] with brackets[] str = str.Replace("[","[[]").Replace("]","[]]");
- Desired result:
[[]Hello World[]] - Actual result:
[[[]]Hello World[]]
The reason, obviously, is the second replacement of an already modified row.
So, how to replace all occurrences of "bad" characters with characters containing "bad" characters?
A quick measurement of all approaches showed that StringBuilder is the most efficient way.
190kb file (all in milliseconds)
regexTime 40.5065 replaceTime 20.8891 stringBuilderTime 6.9776
7MB file
regexTime 1209.3529 replaceTime 403.3985 stringBuilderTime 175.2583
By the way, Johnโs direct StringBuilder approach was twice as fast as Seheโs aggregate.
I made an extension from it:
public static String EncloseChars(this string input, char[] charsToEnclose, String leftSide, String rightSide) { if (charsToEnclose == null || leftSide == null || rightSide == null) throw new ArgumentException("Invalid arguments for EncloseChars", charsToEnclose == null ? "charsToEnclose" : leftSide == null ? "leftSide" : "rightSide"); Array.Sort(charsToEnclose); StringBuilder sb = new StringBuilder(); foreach (char c in input) { if (Array.BinarySearch(charsToEnclose, c) > -1) sb.Append(leftSide).Append(c).Append(rightSide); else sb.Append(c); } return sb.ToString(); } "[Hello World]".EncloseChars(new char[]{'[', ']'},"[","]");
Tim schmelter
source share