標籤:article back ack this var ati tmp net add
代碼編譯執行平台:VS2012+Win32+Debug
1.C++中替換全部指定的子串
下面代碼,作為平時程式碼程式庫的儲備,僅供各位猿友參考:
//替換指定的子串//src:原字串 target:待被替換的子串 subs:替換的子串string replaceALL(const char* src, const string& target,const string& subs) { string tmp(src); string::size_type pos =tmp.find(target),targetSize =target.size(),resSize =subs.size(); while(pos!=string::npos)//found { tmp.replace(pos,targetSize,subs); pos =tmp.find(target, pos + resSize); } return tmp;}
代碼主要說明:
(1)tmp.find(target):尋找子串第一次出現的下標;
(2)string::npos:表示未尋找到子串時返回的數值。
MSDN中規定,其值定義例如以下:static const size_type npos = -1;,轉換為無符號整型unsignned int表示的是string所能容納的最大字元數。
(3)string::size_type (由字串配置器 allocator 定義) 描寫敘述的是 string的size,故需為不帶正負號的整數型別。
由於字串配置器預設以類型size_t 作為 size_type。
2.C++按指定分隔字元切割字串
由於C++中istringstream無法提供按指定字元進行字串的格式化輸入,所以這裡自己實現一個按指定字元進行字串切割,然後再讀取切割後的子串。
//qsort函數須要的比較函數。依照升序排序int comp(const void*a,const void*b){ return *(int*)a-*(int*)b;}//按指定分隔字元切割字串//src:源字串 delimiter:分隔字元集合vector<string> split(const string& src,const string& delimiter) { vector<string> strRes; int maxSubstrNum=src.size(); int* pos=new int[maxSubstrNum]; memset(pos,NULL,maxSubstrNum*sizeof(int)); int j=0; for(int i=0;i<delimiter.size();++i) { string::size_type index=src.find(delimiter[i]); while(index!=string::npos) { pos[j++]=index; index=src.find(delimiter[i],index+1); } } //排序 qsort(pos,j,sizeof(int),comp); //取出第一個子串 string substrFir=src.substr(0,pos[0]); if(substrFir!="") strRes.push_back(substrFir); //取出中間j-1個子串 for(int i=0;i<j-1;++i) { string substr=src.substr(pos[i]+1,pos[i+1]-pos[i]-1); if(substr!="") strRes.push_back(substr); } //取出最後一個子串 string substrLast=src.substr(pos[j-1]+1,src.size()-pos[j-1]-1); if(substrLast!="") strRes.push_back(substrLast); delete[] pos; return strRes;}
代碼主要說明:
(1)利用find()和substr()函數實現切割的功能;
(2)代碼中。須要對切割符出現的下標進行排序。這樣才幹順序的切割符下標取出子字串。
參考文獻
[1]http://blog.sina.com.cn/s/blog_49370c500100ov3k.html
[2]http://www.jb51.net/article/55954.htm
C++實現字串的切割和替換