c++ 实现对字符串按字符分割源代码

2023-05-11,,

//头文件

#include <string>
#include <vector>

//-------------获取按ch分割的子字符串--------------------------
std::vector<std::string> split(char* pStr, char ch)
{
std::vector<std::string> vec;
if (nullptr == pStr)
return vec;

std::string strStr(pStr);
int _off=0;
std::string::size_type sizeType;
while(true)
{
    if (_off>=strStr.length())
        break;

    sizeType=strStr.find_first_of(ch,_off);
    if (sizeType<=0)
    {
        _off=sizeType+1;
        continue;
    }
    if (sizeType==std::string::npos)
    {
        vec.push_back(strStr.substr(_off,strStr.length() - _off));
        break;
    }
    vec.push_back(strStr.substr(_off,sizeType - _off));
    _off=sizeType+1;
}
return vec;

}

//调用实例

std::vector<std::string> vecCapdu = split((char *)strCapdu.c_str(),';');
for (std::vector<std::string>::const_iterator itr=vecCapdu.cbegin();itr!=vecCapdu.cend();itr++)
{

printf("%s",itr->c_str());//迭代器输出

}

《c++ 实现对字符串按字符分割源代码.doc》

下载本文的Word格式文档,以方便收藏与打印。