CPP中字符串分割函数,split

cpp的标准库函数中没有字符串分割函数,而这个函数又是经常需要用到的,有必要写出一个模板,背会以便使用

void split(string str,vector<string> &v,string spacer)
{
    int pos1,pos2;
    int len=spacer.length();     //记录分隔符的长度
    pos1=0;
    pos2=str.find(spacer);
    while( pos2 != string::npos )
    {
        v.push_back( str.substr(pos1,pos2-pos1) );
        pos1 = pos2 + len;
        pos2 = str.find(spacer,pos1);    // 从str的pos1位置开始搜寻spacer
    }
    if(pos1 != str.length()) //分割最后一个部分
       v.push_back(str.substr(pos1));
}
  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在C++,可以使用一些方法来实现英文字符串分割。以下是一种常见的方法: 1. 使用标准库函数: 可以使用C++标准库字符串处理函数来实现字符串分割,例如使用`std::string`的`find`和`substr`函数。 示例代码如下: ```cpp #include <iostream> #include <string> int main() { std::string str = "Hello, 你好"; std::string delimiter = ", "; size_t pos = 0; std::string token; while ((pos = str.find(delimiter)) != std::string::npos) { token = str.substr(0, pos); std::cout << token << std::endl; str.erase(0, pos + delimiter.length()); } std::cout << str << std::endl; return 0; } ``` 运行结果: ``` Hello 你好 ``` 这个示例代码,我们使用了`find`函数来查找分隔符的位置,然后使用`substr`函数来提取子字符串。通过循环不断提取子字符串,直到没有分隔符为止。 2. 使用第三方库: 除了使用标准库函数,还可以使用一些第三方库来实现字符串分割,例如Boost库的`split`函数。 示例代码如下: ```cpp #include <iostream> #include <string> #include <boost/algorithm/string.hpp> int main() { std::string str = "Hello, 你好"; std::vector<std::string> tokens; boost::split(tokens, str, boost::is_any_of(", ")); for (const auto& token : tokens) { std::cout << token << std::endl; } return 0; } ``` 运行结果: ``` Hello 你好 ``` 这个示例代码,我们使用了Boost库的`split`函数来实现字符串分割。该函数字符串按照指定的分隔符进行分割,并将结果存储在一个`std::vector`容器
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值