C++实现字符串的分割和替换

来源:互联网 发布:访客网络什么意思 编辑:程序博客网 时间:2024/05/16 12:58

代码编译运行平台: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

1 0
原创粉丝点击