字符串替换程序 p324

// replace:从str字符串中查找oldVal字符串,如果找到就替换成newVal字符串。
void replace(string &str, const string &oldVal, const string &newVal) {
    string tmp(str, 0, oldVal.size());                // 初始化一个str的子串,用于与oldVal进行比较。
    auto   head = str.begin();                        // 指示tmp的begin()迭代器在str中的位置。
    auto   tail = head + oldVal.size();             // 指示tmp的end()迭代器在str中的位置。
    
    if(str.size() < oldVal.size())                    // 如果str比要查找的字符串还短,直接退出。
        return;
        
    while((tail-1) != str.end()) {                    // tail-1为tmp最后一个字符在str中的位置,只有最后一个字符有效就循环
        if(tmp == oldVal) {                            // 在str中找到了oldVal
            head = str.erase(head, tail);            
            for(const auto &v : newVal) {            // 由于insert(p, b, e)返回的是void,所以使用insert(p, v)循环插入。
                head = str.insert(head, v);
                ++head;                                // 指向插入字符的下一个字符。
            }
            if(str.end() - head >= oldVal.size()) { // 保证剩余的字符长度大于oldVal的长度
                tail = head + oldVal.size();
                tmp.assign(head, tail);
            } else {
                return;
            }
        } else {
            tmp.erase(tmp.begin());                    // 模拟队列操作。这里删除了第一个,string重新分配并复制,不划算。
            tmp.insert(tmp.end(), 1, *tail);           // 这两句替换成tmp = str.substr(head-str.begin(), oldVal.size());
            ++head;
            ++tail;
        }
    }
}

 使用replace和下标版本

// replace:从str字符串中查找oldVal字符串,如果找到就替换成newVal字符串。
void replace(string &str, const string &oldVal, const string &newVal) {
    size_t oldSize = oldVal.size();
    size_t newSize = newVal.size();  // 不能保存一个str.size()的值,应该str在变化,长度也是在变化的。
    string tmp(str, 0, oldSize);
    size_t head = 0;
    
    if(str.size() < oldSize)
        return;
        
    while(head + oldSize <= str.size()) {
        if(tmp == oldVal) {
            str.replace(head, oldSize, newVal);
            head += newSize;
            if(str.size() - head - 1 >= oldSize) {  // "-1"是应为head是从0开始的,少减了一个。
                tmp.assign(str, head, oldSize);
            } else {
                return;
            }
        } else {
            tmp = str.substr(++head, oldSize);
        }
    }
}
原文地址:https://www.cnblogs.com/yuandonghua/p/11393367.html