- if (toReplace.size() == 0)\r
- return *this;\r
-\r
- const T* other = toReplace.c_str();\r
- const T* replace = replaceWith.c_str();\r
- const u32 other_size = toReplace.size();\r
- const u32 replace_size = replaceWith.size();\r
-\r
- // Determine the delta. The algorithm will change depending on the delta.\r
- s32 delta = replace_size - other_size;\r
-\r
- // A character for character replace. The string will not shrink or grow.\r
- if (delta == 0)\r
- {\r
- s32 pos = 0;\r
- while ((pos = find(other, pos)) != -1)\r
- {\r
- for (u32 i = 0; i < replace_size; ++i)\r
- array[pos + i] = replace[i];\r
- ++pos;\r
- }\r
- return *this;\r
- }\r
-\r
- // We are going to be removing some characters. The string will shrink.\r
- if (delta < 0)\r
- {\r
- u32 i = 0;\r
- for (u32 pos = 0; pos < used; ++i, ++pos)\r
- {\r
- // Is this potentially a match?\r
- if (array[pos] == *other)\r
- {\r
- // Check to see if we have a match.\r
- u32 j;\r
- for (j = 0; j < other_size; ++j)\r
- {\r
- if (array[pos + j] != other[j])\r
- break;\r
- }\r
-\r
- // If we have a match, replace characters.\r
- if (j == other_size)\r
- {\r
- for (j = 0; j < replace_size; ++j)\r
- array[i + j] = replace[j];\r
- i += replace_size - 1;\r
- pos += other_size - 1;\r
- continue;\r
- }\r
- }\r
-\r
- // No match found, just copy characters.\r
- array[i] = array[pos];\r
- }\r
- array[i-1] = 0;\r
- used = i;\r
-\r
- return *this;\r
- }\r
-\r
- // We are going to be adding characters, so the string size will increase.\r
- // Count the number of times toReplace exists in the string so we can allocate the new size.\r
- u32 find_count = 0;\r
- s32 pos = 0;\r
- while ((pos = find(other, pos)) != -1)\r
- {\r
- ++find_count;\r
- ++pos;\r
- }\r
-\r
- // Re-allocate the string now, if needed.\r
- u32 len = delta * find_count;\r
- if (used + len > allocated)\r
- reallocate(used + len);\r
-\r
- // Start replacing.\r
- pos = 0;\r
- while ((pos = find(other, pos)) != -1)\r
- {\r
- T* start = array + pos + other_size - 1;\r
- T* ptr = array + used - 1;\r
- T* end = array + delta + used -1;\r
-\r
- // Shift characters to make room for the string.\r
- while (ptr != start)\r
- {\r
- *end = *ptr;\r
- --ptr;\r
- --end;\r
- }\r
-\r
- // Add the new string now.\r
- for (u32 i = 0; i < replace_size; ++i)\r
- array[pos + i] = replace[i];\r
-\r
- pos += replace_size;\r
- used += delta;\r
- }\r