字串替換(C )

2022-02-10 05:18:29 字數 1034 閱讀 9343

用過python的朋友應該知道,python的string中有個replace函式,其功能是實現字串的替換,預設情況下是替換所有,如果加入引數的話會根據設定的個數進行替換,比如下面的例子:

>>> import string

>>> str1 = "ab1ab2ab3ab4"

>>> print string.replace(str1,"ab","cd")

cd1cd2cd3cd4

>>> print string.replace(str1,"ab","cd",1)

cd1ab2ab3ab4

>>> print string.replace(str1,"ab","cd",2)

cd1cd2ab3ab4

>>>

在c++中,我也想這麼用……暫時還沒找到現成的,就自己寫了個。

這裡貼出來函式的**,也方便我以後使用:

string m_replace(string str,string pattern,string dstpattern,int count=-1

) }

}retstr +=str.substr(i);

return

retstr;

}

補充:當時我認為stl的replace函式不能進行不同長度的替換(現在證明是錯的),所以就沒用……

這裡有用stl的replace函式的實現:

view code

#include #include 

using

namespace

std;

string m_replace(string

strsrc,

const

string &oldstr, const

string &newstr,int count=-1

)

return

strret;

}int

main()

C 字串替換

編譯執行平台 vs2017 win32 debug 以下 作為平時 庫的儲備,僅供各位參考 brief 替換指定的子串 param src 原字串 target 待被替換的子串 subs 替換的子串 string replaceall const char src,const string targ...

C 字串替換函式

include include include char strreplace char src,char rpl,char dest free temp return buf 在作專案過程中發現,c語言中並沒有字串替換相關的函式,所有就自己寫了乙個,不過此程式也存在一定的缺陷,就是字串越界問題,因...

C語言字串替換

define crt secure no warnings include include include 有字串有以下特徵 abcd11111abcd2222abcdqqqqq 求寫乙個函式,輸出以下結果 把字串替換成 dcba11111dcba2222dcbaqqqqq 並把結果傳出。要求 1....