To develop my understanding of C++, I've written an overload function that allows users to use & to insert strings within other strings (denoted by a $ character). So far, it only works with one replacement in a string. For example:
"Hello $" & "World" -> "Hello World"
I want to receive feedback, because I'm sure there's a much better way than using three for loops. And I'd like a better foundation before moving forward with multiple replacements in a single string.
#include <string>
#include <iostream>
std::string operator&(const std::string& str, const char* cstr) {
if (str.empty()) {
return std::string(cstr);
}
if (str.find("$") == std::string::npos) {
return str + std::string(cstr);
}
int string_length = str.length();
int cstr_length = 0;
while (cstr[cstr_length] != '\0') {
cstr_length++;
}
int length = string_length + cstr_length;
std::string result = "";
int i;
for (i = 0; i < str.find("$"); i++) {
result += str[i];
}
i++; // Skips past the '$'
for (int j = 0; j < cstr_length; j++) {
result += cstr[j];
}
for (; i < string_length; i++) {
result += str[i];
}
return result;
}
int main(int argc, char** argv) {
std::string string = "Hello $, My name is Ben!";
char* cstr = (char*)"World";
std::string result = string & cstr;
std::cout << result << std::endl;
return 0;
}
'%'character as the insertion point I would change to using that over the'$'/ \$\endgroup\$