C++實現字符串的切割和替換
阿新 • • 發佈:2017-07-03
spa () acea del 表示 平臺 return all data-
代碼編譯執行平臺: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++實現字符串的切割和替換