Advertisement
magnusbakken

utf-16 aware substring replace

Feb 10th, 2016
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.54 KB | None | 0 0
  1.         public static string ReplaceSubstring(this string s, string replacement, int startIndex, int length)
  2.         {
  3.             if (s == null)
  4.                 throw new ArgumentNullException("s", "Input string cannot be null");
  5.             else if (startIndex < 0)
  6.                 throw new ArgumentOutOfRangeException("startIndex", "startIndex cannot be negative");
  7.             else if (length < 0)
  8.                 throw new ArgumentOutOfRangeException("length", "length cannot be negative");
  9.  
  10.             var endIndex = startIndex + length;
  11.             int index = 0, actualFrom = 0, actualTo = 0;
  12.             var foundFrom = false;
  13.             foreach (var c in s)
  14.             {
  15.                 if (index == endIndex)
  16.                     break;
  17.                 else if (index == startIndex)
  18.                     foundFrom = true;
  19.  
  20.                 if (!char.IsHighSurrogate(c))
  21.                     index++;
  22.  
  23.                 if (!foundFrom)
  24.                     actualFrom++;
  25.  
  26.                 actualTo++;
  27.             }
  28.  
  29.             if (startIndex > index)
  30.                 throw new ArgumentOutOfRangeException("startIndex", $"\"startIndex\" argument is outside string boundaries: {startIndex} > {index}");
  31.             else if (endIndex > index)
  32.                 throw new ArgumentOutOfRangeException("length", $"\"length\" argument is outside string boundaries: {endIndex} > {index}");
  33.  
  34.             return string.Concat(
  35.                 s.Substring(0, actualFrom),
  36.                 replacement,
  37.                 s.Substring(actualTo));
  38.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement