使用带std :: string的strtok [英] Using strtok with a std::string

查看:420
本文介绍了使用带std :: string的strtok的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,我想标记。
但是C strtok()函数需要我的字符串为 char *
我如何做到这一点?

I have a string that I would like to tokenize. But the C strtok() function requires my string to be a char*. How can I do this simply?

我试过:

token = strtok(str.c_str(), " "); 

这会失败,因为它会变成 const char * ,而不是 char *

which fails because it turns it into a const char*, not a char*

推荐答案

#include <iostream>
#include <string>
#include <sstream>
int main(){
    std::string myText("some-text-to-tokenize");
    std::istringstream iss(myText);
    std::string token;
    while (std::getline(iss, token, '-'))
    {
        std::cout << token << std::endl;
    }
    return 0;
}

或者,如上所述,使用boost更具灵活性。

Or, as mentioned, use boost for more flexibility.

这篇关于使用带std :: string的strtok的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆