Pages

Tuesday, March 19, 2019

A Unicode "ReplaceAt" string extension method handles Unicode string properly

Most "ReplaceAt" commonly methods seen online fail when replace a character at a specific position in a Unicode string.

Unicode String Replace At Issue

Lets examine Unicode string "🎢πŸ”₯Γ©-"

🎢 Unicode Character 'MULTIPLE MUSICAL NOTES' (U+1F3B6) - 4-byte Unicode character
πŸ”₯ Fire Emoji U+1F525 - 4-byte Unicode character
Γ©  Latin Small Letter e with Acute U+00E9 - 2-byte Unicode character
Unicode Character 'HYPHEN-MINUS' (U+002D) - 2-byte Unicode character

😊 Smiling Face with Smiling Eyes Emoji U+1F60A - 4-byte Unicode character (replacement)



🎢πŸ”₯Γ©- is length of 6, but there are ONLY 4 characters! Why not len=4?
🎢πŸ”₯ are double byte UNICODE characters (> \u10000) of width or len 2 each 
🎢πŸ”₯Γ©- below will replace space after lasting character '-' (position 4) with a sub using most common techniques seen online

This is due to the fact that Unicode code points outside of the Basic Multilingual Plane (BMP) > U+FFFF, are are represented in UTF-16 using 4 byte surrogate pairs, rather than using 2 bytes. 


Specifically, the High Surrogate (U+D800–U+DBFF) and Low Surrogate (U+DC00–U+DFFF) codes are reserved for encoding non-BMP characters in UTF-16 by using a pair of 16-bit codes: one High Surrogate and one Low Surrogate. A single surrogate code point will never be assigned a character.

To correctly count the number of characters in a string that may contain code points higher than U+FFFF, you can use the StringInfo class (from System.Globalization).

Below is an large enumeration of common ReplaceAt implementations available on internet. They all fail, except for one that using StringInfo. . 

UnicocodeReplaceAt method replaces a character in a string at specific zero-based index and handles null char '\0' properly, by removing if from resultant string. 





  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
using System.Linq;
using System.Diagnostics;
using System;
using System.Text;
using System.Globalization;

//Created for 
//http://metadataconsulting.blogspot.com/2019/03/A-Unicode-ReplaceAt-string-extension-method-handles-Unicode-string-properly.html

public static class Program
{

 
 const char cEMPTY = '\0'; 
    static readonly string EMPTY = cEMPTY.ToString(); 
 
 public static string UnicodeReplaceAtFastest(this string s, int idx, string replace)
    {
        // This StringBuilder holds the output results.
        StringBuilder sb = new StringBuilder();

      // Use the ParseCombiningCharacters method to 
      // get the index of each real character in the string.
      Int32[] textElemIndex = StringInfo.ParseCombiningCharacters(s);
    
      if (string.IsNullOrEmpty(s)) return s;
      if (idx < 1) 
          return s; 

      string newstring = string.Empty;
      if (textElemIndex.Length == 1) {
          return replace; 
      }
      else if (idx < textElemIndex.Length)
      {
          idx = idx - 1; 
       return s.Remove(textElemIndex[idx], textElemIndex[idx + 1] - textElemIndex[idx]).Insert(textElemIndex[idx], replace.ToString()); 

      }
   else if (idx == textElemIndex.Length)
   {
    idx = idx - 1;
    return s.Remove(textElemIndex[idx], s.Length - textElemIndex[idx]).Insert(textElemIndex[idx], replace.ToString());

   }
      else
          return s; 
        
    }

 
 public static string UnicodeReplaceAtFast(this string s, int idx, string replace)
    {
        // This StringBuilder holds the output results.
        StringBuilder sb = new StringBuilder();

        // Use the enumerator returned from GetTextElementEnumerator 
        // method to examine each real character.
        TextElementEnumerator charEnum = StringInfo.GetTextElementEnumerator(s);

        if (string.IsNullOrEmpty(s)) return s;
        if (idx < 1)
            return s;

        //string newstring = string.Empty;
        //if (textElemIndex.Length == 1)
        //{
        //    return replace;
        //}
        //else if (idx <= textElemIndex.Length)
        //{
            idx = idx - 1;

            while (charEnum.MoveNext())
            {
                if (charEnum.ElementIndex != idx)
                    sb.Append(charEnum.GetTextElement()); 
                else
     sb.Append(replace);
                    
                // i++;   
            }

            return sb.ToString();

        //}
        //else
        //    return s;

    }
 
    public static string UnicodeReplaceAt(this string str, int offset, char replaceChar)
    {
        int count = 1; //number of characters to remove at location offset
        string replaceBy = replaceChar.ToString();
        return new StringInfo(str).ReplaceByPosition(replaceBy, offset, count).String;
    }

    public static StringInfo ReplaceByPosition(this StringInfo str, string replaceBy, int offset, int count)
    {
        if (replaceBy != EMPTY)
            return str.RemoveByTextElements(offset, count).InsertByTextElements(offset, replaceBy);
  else if (!string.IsNullOrEmpty(replaceBy))
   return str.RemoveByTextElements(offset, count).InsertByTextElements(offset, replaceBy);
        else
            return str.RemoveByTextElements(offset, count);
    }

    public static StringInfo RemoveByTextElements(this StringInfo str, int offset, int count)
    { 
  //Tue 20-Aug-19 11:32am metadataconsulting.ca - replaceat index > string.len return orginal string
  if (offset > str.LengthInTextElements)
   return str;
  
        return new StringInfo(string.Concat(
            str.SubstringByTextElements(0, offset),
            offset + count < str.LengthInTextElements
                ? str.SubstringByTextElements(offset + count, str.LengthInTextElements - count - offset)
                : string.Empty
            ));
    }
    public static StringInfo InsertByTextElements(this StringInfo str, int offset, string insertStr)
    {
        //Tue 20-Aug-19 11:32am metadataconsulting.ca - replaceat index > string.len return orginal string
  if (offset > str.LengthInTextElements)
   return str;
  
  if (string.IsNullOrEmpty(str.String))
            return new StringInfo(insertStr);

        return new StringInfo(string.Concat(
            str.SubstringByTextElements(0, offset),
            insertStr,
            str.LengthInTextElements - offset > 0 ? str.SubstringByTextElements(offset, str.LengthInTextElements - offset) : ""
        ));
    }

    public static string SubsituteStringStringBuilder(this string s, int idx, char replaceChar)
    {
        if (string.IsNullOrEmpty(s) || idx >= s.Length || idx < 0)
            return s;

        return new StringBuilder(s).Remove(idx, 1).Insert(idx, replaceChar.ToString()).ToString();
    }

    public static string ReplaceAtSubstring(this string s, int idx, char replaceChar)
    {
        if (string.IsNullOrEmpty(s) || idx >= s.Length || idx < 0)
            return s;

        return s.Substring(0, idx) + replaceChar.ToString() + s.Substring(idx + replaceChar.ToString().Length, s.Length - (idx + replaceChar.ToString().Length));

    }

    public static string ReplaceAtStringManipulation(this string s, int idx, char replaceChar)
    {
        if (string.IsNullOrEmpty(s) || idx >= s.Length || idx < 0)
            return s;

        return s.Remove(idx, 1).Insert(idx, replaceChar.ToString());
    }

    public static string ReplaceAtLinq(this string value, int index, char newchar)
    {
        if (value.Length <= index)
            return value;
        else
            return string.Concat(value.Select((c, i) => i == index ? newchar : c));
    }

    public static string ReplaceAtCharArray(this string input, uint index, char newChar)
    {
        if (string.IsNullOrEmpty(input) || index >= input.Length)
            return input;

        char[] chars = input.ToCharArray();
        chars[index] = newChar;
        return new string(chars);
    }

    public static void Main()
    {
        //In .NET 4.5 and later also UTF-16 is supported
        //Console.OutputEncoding = System.Text.Encoding.Unicode;  
        
  //Γ©  Latin Small Letter e with Acute U+00E9 - single byte Unicode character
  //😊 Smiling Face with Smiling Eyes Emoji U+1F60A - double byte Unicode character
  //🎢 Multiple Musical Notes Emoji U+1F3B6 - - double byte Unicode character
  //πŸ”₯ Fire Emoji U+1F525 -- double byte Unicode character
  
  Console.WriteLine("Unicode String Replace At Issue");
  Console.WriteLine("Lets examine string \"🎢πŸ”₯Γ©-\"");  
        Console.WriteLine("🎢πŸ”₯Γ©- is length of " + "🎢πŸ”₯Γ©-".Length + ", but there are ONLY 4 characters! Why not len=4?"); 
  Console.WriteLine("🎢πŸ”₯ are double byte UNICODE characters (> \\u10000) of width or len 2 each ");
  Console.WriteLine("🎢πŸ”₯Γ©- below will replace space after lasting character '-' (position 4) with a sub using most common techniques seen online"); 
  
  Console.WriteLine(); 
  
  Stopwatch sw = new Stopwatch();
        sw.Start();
        Console.WriteLine("🎢πŸ”₯Γ©- using ReplaceAtCharArray".ReplaceAtCharArray(4, 'X'));
        sw.Stop();
        Console.WriteLine("in {0} ticks.", sw.ElapsedTicks.ToString("N0"));

        sw.Restart();
        Console.WriteLine("🎢πŸ”₯Γ©- using ReplaceAtLinq".ReplaceAtLinq(4, 'Y'));
        sw.Stop();
        Console.WriteLine("in {0} ticks.", sw.ElapsedTicks.ToString("N0"));

        sw.Restart();
        Console.WriteLine("🎢πŸ”₯Γ©- using ReplaceAtStringManipulation".ReplaceAtStringManipulation(4, 'Z'));
        sw.Stop();
        Console.WriteLine("in {0} ticks.", sw.ElapsedTicks.ToString("N0"));

        sw.Restart();
        Console.WriteLine("🎢πŸ”₯Γ©- using ReplaceAtSubstring".ReplaceAtSubstring(4, 'A'));
        sw.Stop();
        Console.WriteLine("in {0} ticks.", sw.ElapsedTicks.ToString("N0"));

        sw.Restart();
        Console.WriteLine("🎢πŸ”₯Γ©- using SubsituteStringStringBuilder".SubsituteStringStringBuilder(4, 'W'));
        sw.Stop();
        Console.WriteLine("in {0} ticks.", sw.ElapsedTicks.ToString("N0"));

  sw.Restart();
        Console.WriteLine("🎢πŸ”₯Γ©- using UnicodeReplaceAt".UnicodeReplaceAt(4, '4'));
        sw.Stop();
        Console.WriteLine("in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
  
  Console.WriteLine(); 
  Console.WriteLine("UnicodeReplaceAt replaces properly at position 4 in zero based index string");
        Console.WriteLine(); 
  sw.Restart();
        Console.Write("🎢πŸ”₯Γ©- using UnicodeReplaceAt(0, '0')".UnicodeReplaceAt(0, '0'));
        sw.Stop();
  Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
  sw.Restart();
        Console.Write("🎢πŸ”₯Γ©- using UnicodeReplaceAt(1, '1')".UnicodeReplaceAt(1, '1'));
        sw.Stop();
  Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
  sw.Restart();
        Console.Write("🎢πŸ”₯Γ©- using UnicodeReplaceAt(2, '2')".UnicodeReplaceAt(2, '2'));
        sw.Stop();
  Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
  sw.Restart();
        Console.Write("🎢πŸ”₯Γ©- using UnicodeReplaceAt(3, '3')".UnicodeReplaceAt(3, '3'));
        sw.Stop();
  Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
  sw.Restart();
        Console.Write("🎢πŸ”₯Γ©- using UnicodeReplaceAt(4, '4')".UnicodeReplaceAt(4, '4'));
        sw.Stop();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
     Console.Write("🎢πŸ”₯Γ©-".UnicodeReplaceAt(5, '5')+" using UnicodeReplaceAt(5, '5') - this is beyond end of string, so return orginal string");
        sw.Stop();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
        
  Console.WriteLine(); 
  Console.WriteLine(); 
  Console.WriteLine(" FAST testing.");
  Console.WriteLine(); 
  Console.WriteLine(); 
  
  sw.Reset();
        sw.Start();
        Console.Write("🎢πŸ”₯Γ©-a\u0304\u0308bc\u0327".UnicodeReplaceAtFast(5, "😊") + " using UnicodeReplaceAtFast(5, '😊') - cool but still O(100) more :(");
        sw.Stop();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));


        sw.Reset();
        sw.Start();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
        Console.Write("a\u0304".UnicodeReplaceAtFast(1, "😊") + " using UnicodeReplaceAtFast(1, '😊') - bounds check - 1 char");
        sw.Stop();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));

        sw.Reset();
        sw.Start();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
        Console.Write("a\u0304".UnicodeReplaceAtFast(0, "😊") + " using UnicodeReplaceAtFast(0, '😊') - bounds check - wrong index");
        sw.Stop();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
    
  Console.WriteLine(); 
  Console.WriteLine(); 
  Console.WriteLine(" FASTEST testing.");
  Console.WriteLine(); 
  Console.WriteLine(); 
  
  sw.Reset();
        sw.Start();
        Console.Write("🎢πŸ”₯Γ©-a\u0304\u0308bc\u0327".UnicodeReplaceAtFastest(5, "😊") + " using UnicodeReplaceAtFastest(5, '😊') - cool but still O(100) more than string.Replace :(");
        sw.Stop();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));


        sw.Reset();
        sw.Start();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
        Console.Write("a\u0304".UnicodeReplaceAtFastest(1, "😊") + " using UnicodeReplaceAtFastest(1, '😊') - bounds check - 1 char");
        sw.Stop();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));

        sw.Reset();
        sw.Start();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
        Console.Write("a\u0304".UnicodeReplaceAtFastest(0, "😊") + " using UnicodeReplaceAtFastest(0, '😊') - bounds check - 0 index");
        sw.Stop();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
    
  sw.Reset();
        sw.Start();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
        Console.Write("a\u0304".UnicodeReplaceAtFastest(5, "😊") + " using UnicodeReplaceAtFastest(5, '😊') - bounds check - after end index");
        sw.Stop();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
    
  sw.Reset();
        sw.Start();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
        Console.Write("🎢πŸ”₯Γ©-a\u0304\u0308bc\u0327".UnicodeReplaceAtFastest(6, "😊") + " using UnicodeReplaceAtFastest(6, '😊') - bounds check - after end index");
        sw.Stop();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
    
  sw.Reset();
        sw.Start();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
        Console.Write("🎢πŸ”₯Γ©-a\u0304\u0308bc\u0327".UnicodeReplaceAtFastest(7, "😊") + " using UnicodeReplaceAtFastest(7, '😊') - bounds check - after end index");
        sw.Stop();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
    
  sw.Reset();
        sw.Start();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
        Console.Write("🎢πŸ”₯Γ©-a\u0304\u0308bc\u0327".UnicodeReplaceAtFastest(8, "😊") + " using UnicodeReplaceAtFastest(8, '😊') - bounds check - after end index");
        sw.Stop();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
    

  Console.WriteLine(); 
  Console.WriteLine("String.Replace works, but replaces all characters, not at specific location as above functions");
        Console.WriteLine(); 
  sw.Reset();
        sw.Start();
  Console.Write("🎢πŸ”₯Γ©- using String.Replace".Replace("πŸ”₯", "+") + "('πŸ”₯', '+')");
        sw.Stop();
        Console.WriteLine(" in {0} ticks.", sw.ElapsedTicks.ToString("N0"));
  
    }
}

Output
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
Unicode String Replace At Issue
Lets examine string "🎢πŸ”₯Γ©-"
🎢πŸ”₯Γ©- is length of 6, but there are ONLY 4 characters! Why not len=4?
🎢πŸ”₯ are double byte UNICODE characters (> \u10000) of width or len 2 each 
🎢πŸ”₯Γ©- below will replace space after lasting character '-' (position 4) with a sub using most common techniques seen online

🎢πŸ”₯X- using ReplaceAtCharArray
in 2,089 ticks.
🎢πŸ”₯Y- using ReplaceAtLinq
in 3,724 ticks.
🎢πŸ”₯Z- using ReplaceAtStringManipulation
in 1,411 ticks.
🎢πŸ”₯A- using ReplaceAtSubstring
in 1,768 ticks.
🎢πŸ”₯W- using SubsituteStringStringBuilder
in 1,701 ticks.
🎢πŸ”₯Γ©-4using UnicodeReplaceAt
in 5,811 ticks.

UnicodeReplaceAt replaces properly at position 4 in zero based index string

0πŸ”₯Γ©- using UnicodeReplaceAt(0, '0') in 31 ticks.
🎢1é- using UnicodeReplaceAt(1, '1') in 24 ticks.
🎢πŸ”₯2- using UnicodeReplaceAt(2, '2') in 23 ticks.
🎢πŸ”₯Γ©3 using UnicodeReplaceAt(3, '3') in 76 ticks.
🎢πŸ”₯Γ©-4using UnicodeReplaceAt(4, '4') in 22 ticks.
🎢πŸ”₯Γ©- using UnicodeReplaceAt(5, '5') - this is beyond end of string, so return orginal string in 22 ticks.


 FAST testing.


🎢πŸ”₯😊-ā̈bç using UnicodeReplaceAtFast(5, '😊') - cool but still O(100) more :( in 2,014 ticks.
 in 3 ticks.
😊 using UnicodeReplaceAtFast(1, '😊') - bounds check - 1 char in 23 ticks.
 in 3 ticks.
ā using UnicodeReplaceAtFast(0, '😊') - bounds check - wrong index in 19 ticks.


 FASTEST testing.


🎢πŸ”₯Γ©-😊bç using UnicodeReplaceAtFastest(5, '😊') - cool but still O(100) more than string.Replace :( in 2,155 ticks.
 in 2 ticks.
😊 using UnicodeReplaceAtFastest(1, '😊') - bounds check - 1 char in 23 ticks.
 in 3 ticks.
ā using UnicodeReplaceAtFastest(0, '😊') - bounds check - 0 index in 21 ticks.
 in 3 ticks.
😊 using UnicodeReplaceAtFastest(5, '😊') - bounds check - after end index in 63 ticks.

String.Replace works, but replaces all characters, not at specific location as above functions

🎢+Γ©- using String.Replace('πŸ”₯', '+') in 15 ticks.


No comments:

Post a Comment