亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何替換字符串中出現的所有字符?

如何替換字符串中出現的所有字符?

C++
慕萊塢森 2019-07-01 16:28:18
如何替換字符串中出現的所有字符?中的其他字符替換所有出現的字符的有效方法是什么?std::string?
查看完整描述

3 回答

?
眼眸繁星

TA貢獻1873條經驗 獲得超9個贊

問題集中在character替換,但是,正如我發現這個頁面非常有用(特別是康拉德),我想分享一下這個更廣義的實現,它允許處理substrings此外:

std::string ReplaceAll(std::string str, const std::string& from, const std::string& to) {
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
    }
    return str;}

用法:

std::cout << ReplaceAll(string("Number Of Beans"), std::string(" "), std::string("_")) << std::endl;std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("X")) << std::endl;std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("h")) << std::endl;

產出:

豆子數

xjxxgtXty

赫赫加斯蒂


編輯:

以上內容可以更合適的方式實現,如果您需要考慮性能,請不要返回任何內容(void)并直接在字符串上執行更改str作為論據,通過按地址而不是按價值計算..這將避免無用和昂貴的原始字符串副本,同時返回結果。你說了算那.。

代碼:

static inline void ReplaceAll2(std::string &str, const std::string& from, const std::string& to){
    // Same inner code...
    // No return statement}

希望這對其他人有幫助.。


查看完整回答
反對 回復 2019-07-01
  • 3 回答
  • 0 關注
  • 1252 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號