Program:
void foo() {
string sourceStr = "Tag:贾鑫@VoltDB";
string insertStr = "XinJia";
int start = 4;
int length = 2;
sourceStr.erase(start, length);
sourceStr.insert(start, insertStr);
cout << sourceStr << endl;
}
For this program, I want to get output as "Tag:XinJia@VoltDB", but it seems that the std string erase and insert does not work for UTF-8 string.
Is there any boost library that I can use? How should I solve this problem?
After talking with others, I realize that there is no standard library that can solve this problem. So I write a function to do my work and would like to share it with others who have this similar problem:
std::string overlay_function(const char* sourceStr, size_t sourceLength,
std::string insertStr, size_t startPos, size_t length) {
int32_t i = 0, j = 0;
while (i < sourceLength) {
if ((sourceStr[i] & 0xc0) != 0x80) {
if (++j == startPos) break;
}
i++;
}
std::string result = std::string(sourceStr, i);
result.append(insertStr);
bool reached = false;
j = 0;
while (i < sourceLength) {
if ((sourceStr[i] & 0xc0) != 0x80) {
if (reached) break;
if (++j == length) reached = true;
}
i++;
}
result.append(std::string(&sourceStr[i], sourceLength - i));
return result;
}
With this funciton, my program can be:
cout << overlay_function(sourceStr, sourceStr.length(), 4+1, 2) << endl;
Hope it helps.