Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static public string Replace(string original, string pattern, string replacement, StringComparison comparisonType)
- {
- return Replace(original, pattern, replacement, comparisonType, -1);
- }
- static public string Replace(string original, string pattern, string replacement, StringComparison comparisonType, int stringBuilderInitialSize)
- {
- if (original == null)
- {
- return null;
- }
- if (String.IsNullOrEmpty(pattern))
- {
- return original;
- }
- int posCurrent = 0;
- int lenPattern = pattern.Length;
- int idxNext = original.IndexOf(pattern, comparisonType);
- StringBuilder result = new StringBuilder(stringBuilderInitialSize < 0 ? Math.Min(4096, original.Length) : stringBuilderInitialSize);
- while (idxNext >= 0)
- {
- result.Append(original, posCurrent, idxNext - posCurrent);
- result.Append(replacement);
- posCurrent = idxNext + lenPattern;
- idxNext = original.IndexOf(pattern, posCurrent, comparisonType);
- }
- result.Append(original, posCurrent, original.Length - posCurrent);
- return result.ToString();
- }
- // ============================================================ Example 2
- private static string ReplaceEx(string original, string pattern, string replacement)
- {
- int count, position0, position1;
- count = position0 = position1 = 0;
- string upperString = original.ToUpper();
- string upperPattern = pattern.ToUpper();
- int inc = (original.Length/pattern.Length) * (replacement.Length-pattern.Length);
- char [] chars = new char[original.Length + Math.Max(0, inc)];
- while((position1 = upperString.IndexOf(upperPattern, position0)) != -1)
- {
- for ( int i=position0 ; i < position1 ; ++i )
- chars[count++] = original[i];
- for ( int i=0 ; i < replacement.Length ; ++i )
- chars[count++] = replacement[i];
- position0 = position1+pattern.Length;
- }
- if ( position0 == 0 ) return original;
- for ( int i=position0 ; i < original.Length ; ++i )
- chars[count++] = original[i];
- return new string(chars, 0, count);
- }
- //=============================================================
- // Souce: Internet
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement