2015-02-08 65 views
0

我在尋找替換全部算法,它在特定位置後替換所有出現的子字符串。到目前爲止,我有replace all copy的方法。除了this one之外,沒有分配新字符串,最方便的方法是什麼?是否存在方便的方法來提升呢?在特定位置後替換所有出現的搜索字符串

#include <iostream> 
#include <string> 
#include <boost/algorithm/string/replace.hpp> 

int main() { 
    std::string str = "1234 abc1234 marker 1234 1234 123 1 12 134 12341234"; 

    const std::string marker("marker"); 
    size_t pos = str.find(marker); 
    if (pos == std::string::npos) { 
     return 0; 
    } 
    pos += marker.length(); 
    std::string str_out(str, 0, pos); 
    boost::algorithm::replace_all_copy(std::back_inserter(str_out), str.substr(pos, std::string::npos), "12", "XXXX"); 
    std::cout << str << std::endl; 
    std::cout << str_out << std::endl; 
} 

回答

0

如果您想要執行就地查找和替換操作,您必須注意性能影響。爲了做這樣的操作,您可能必須向後讀取可能導致緩存行爲不正確的字符串,或者執行大量內存洗牌,這也會對性能造成影響。一般來說,最好做一個副本替換操作,因爲你將要操作的任何字符串可能會相對較小,並且大多數內存緩存會很容易地處理事情。

如果您必須具有就地查找和替換算法,請使用以下代碼(如果您只是查找插入函數)。我對它進行了基準測試,速度非常快。

std::string& find_replace_in_place(std::string &haystack, const std::string needle, const std::string replacement, size_t start = 0){ 
    size_t ret = 0; 
    size_t position = haystack.find(needle, start); 
    while(position != std::string::npos){ 
     haystack.replace(position, needle.length(), replacement); 
     position = haystack.find(needle, position + replacement.length()); 
    } 
    return haystack; 
} 
相關問題