I'm working on a string manipulation code in C++ for my assignment, where I have to find a substring within a string and essentially replace it with a newly computed sequence based on other inputs (here, the string vector 'patterns'). I have been trying to find a better way to manipulate the string in order to increase efficiency (reduce space cost and possibly also reduce time complexity further). This is a sample of what I've done so far(Sorry if the strings look a bit weird, this was the best simple example I could come up with at the moment):
// some input variables
std::string& originalString ("__ BB ++ AA __ AA __ CC __ DD");
std::map<std::string, std::vector<std::string>> patternMap = {
{"AA", {"aaa","AAA"}},
{"BB", {"bbb","BBB"}},
};
std::size_t location = 0;
while ((location = originalString.find("__", location)) != std::string::npos) {
const std::string subString = originalString.substr(location+4, location+6);
std::map<std::string, std::vector<std::string>>::iterator patternsIterator = patternMap.find(subString);
if (patternsIterator != patternMap.end()) {
const std::vector<std::string> patterns = patternsIterator -> second;
std::string alternateSubString("*");
for (const std::string& item : patterns) {
alternateSubString.append(item + "__" );
}
alternateSubString.replace(alternateSubString.size() - 5, 5,"*");
originalString.replace(location+4, 2, alternateSubString);
location += alternateSubString.size();
}
++location;
}// Expected value of the original string should change to: "__ *bbb__BBB* ++ AA __ *aaa__AAA* __ CC __ DD"
'''
Any tips regarding a better way, maybe do away with the variable alternateSubString? Trying to achieve some space/time optimization here.
Aucun commentaire:
Enregistrer un commentaire