C++ -- string分割

#include "cocos2d.h"
#include <iostream>
#include <vector>
using namespace std;

std::vector<std::string> split2(std::string str, std::string pattern)
{
    std::string::size_type pos;
    std::vector<std::string> result;
    //扩展字符串以方便操作
    str+=pattern;   
    int size=str.size();
    
    for(int i=0; i<size; i++)
    {
        pos=str.find(pattern,i);
        if(pos<size)
        {
            std::string s=str.substr(i,pos-i);
            result.push_back(s);
            i=pos+pattern.size()-1;
        }
    }
    return result;
}


int main(int argc, char *argv[]) {
    
    string str = "HTTP/1.1 200 OK\r\nServer: Apache-Coyote/1.1\r\nContent-Type: application/json;charset=UTF-8\r\nTransfer-Encoding: chunked\r\nDate: Mon, 02 Feb 2015 05:30:40 GMT\r\n\r\n\n";
    string pattern = "\n";
    
    std::vector<string> v = split2(str, pattern);
    
    std::vector<std::string>::iterator it = v.begin();
    for (; it != v.end(); it++) {
        std::string oneLine = *it;
        CCLOG("%s\n",oneLine.c_str());
    }

}

//结果

Cocos2d: HTTP/1.1 200 OK

Cocos2d: Server: Apache-Coyote/1.1

Cocos2d: Content-Type: application/json;charset=UTF-8

Cocos2d: Transfer-Encoding: chunked

Cocos2d: Date: Mon, 02 Feb 2015 05:30:40 GMT

Cocos2d: 

Cocos2d: 

Cocos2d: 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中,`std::string` 类型的字符串分割通常涉及到将一个字符串分解成多个子串,这可以通过不同的方法实现,如使用 `std::getline()`、`substr()` 函数或者自定义迭代器。这里以 `std::getline()` 和 `substr()` 为例: 1. **使用 `std::getline()`**: `std::getline` 从输入流中逐行读取数据,并且可以用来处理包含空格或其他分隔符的字符串。例如,如果有一个逗号分隔的字符串列表,你可以这样做: ```cpp std::ifstream file("data.txt"); std::string line; std::vector<std::string> words; while (std::getline(file, line)) { size_t pos = 0; std::string word; while ((pos = line.find(",")) != std::string::npos) { word = line.substr(0, pos); words.push_back(word); line.erase(0, pos + 1); // 移除已找到的分隔符 } words.push_back(line); // 添加最后一部分,如果没有分隔符 } ``` 2. **使用 `substr()` 和 `find()`**: 如果你知道要分割的字符(如空格或特定字符),可以使用 `substr()` 和 `find()` 方法循环提取子串: ```cpp std::string str = "Hello World, C++ Programming"; std::vector<std::string> parts; size_t start = 0; while (start < str.size()) { size_t end = str.find(' ', start); if (end == std::string::npos) { // 如果没有找到空格,直到字符串末尾 end = str.size(); } parts.push_back(str.substr(start, end - start)); start = end + 1; // 更新起始位置 } parts.erase(parts.begin()); // 去除最后一个可能的空字符串 ``` **相关问题--:** 1. `std::getline()` 和 `substr()` 分别用于什么场景? 2. 如何用C++实现不区分空格的连续字符串分割? 3. 如果我想使用其他分隔符,如何修改上述代码?

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值