c++提取子串

下面的函数GetSub可以从源字符串srcStr中获取所有以begPtn开始且以endPtn结束的子串,并将所获取的子串保存到vector里,例如
可以从字符串"sadfasdfsf#sdaf989789$#asdfasf894325445$#456123asdf$"中获取以“#”开头,以“$”结束的所有子串。

#include 
#include 
#include 
using namespace std;

/*
 get all substrings which start with 'begPth' and end with 'endPtn' (but not include 'endPtn')
 from string srcStr,all of these substings will be stored in vector and then returned

*/
vector GetSub(string srcStr,string begPtn,string endPtn)
{
    vector result;
    if(srcStr.empty())
        return result;        
 
    string::size_type iSrcLen = 0;
    iSrcLen = srcStr.size();
    string::size_type iBegPos = 0, iEndPos = 0;
    while(iBegPos <= iSrcLen)
    {
        //从上个子串的结束位置开始查找下个字串的起始位置
        iBegPos = srcStr.find(begPtn,iEndPos);
        if(iSrcLen <= iBegPos)
            break;
        //从子串的起始位置开始查找其结束位置
        iEndPos = srcStr.find(endPtn,iBegPos+1);
        if(iEndPos < iBegPos)
            break;
        string subStr = srcStr.substr(iBegPos+1,iEndPos-iBegPos-1);
        result.push_back(subStr);
    }
    return result;
}

int main()
{
    string srcStr = "sadfasdfsf#sdaf989789$#asdfasf894325445$#456123asdf$";
    string begPtn = "#";
    string endPtn = "#";
    vector strlist = GetSub(srcStr,begPtn,endPtn);
    vector::iterator iter_beg = strlist.begin();
    vector::iterator iter_end = strlist.end();
    cout<<"srcStr = "<>cStop;

    return 0;
}

 

你可能感兴趣的:(c++提取子串)