【问题标题】:C++ split string class in function not using strtok()函数中的 C++ 拆分字符串类不使用 strtok()
【发布时间】:2019-03-25 12:11:13
【问题描述】:

我有一个默认的构造函数,它接受一个字符串类变量(不是char*),并且需要用分隔符标记该字符串,在我的特殊情况下是逗号。由于我使用的是字符串类,因此我无法使用strtok(),因为它需要char* 作为输入而不是字符串类。鉴于下面的代码,鉴于前两个标记是字符串,第三个是 in 和第四个是 double,我如何将字符串拆分为更小的字符串?

private string a;
private string b;
private int x;
private double y;

StrSplit::StrSplit(string s){
  a = // tokenize the first delimiter and assign it to a
  b = // tokenize the second delimiter and assign it to b
  x = // tokenize the third delimiter and assign it to x
  y = // tokenize the fourth delimiter and assign it to y
}

【问题讨论】:

  • 你能把 s.cstr() 变成 strtok(delimiter,s.cstr()) 吗?可以参考:cplusplus.com/reference/string/string/c_str
  • 同时使用#include string 和#include cstring s.cstr() 导致“std::string”没有名为“cstr”的成员”
  • 应该是c_str()
  • Maverick 就是这样。我现在唯一遇到的问题是:“警告:不推荐将字符串常量转换为‘char*’[-Wwrite-strings]。”我想解决这个错误,但不知道如何开始。

标签: c++ string split token tokenize


【解决方案1】:

试试下面 源代码:(test it online)

#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <cstdlib>

std::string a;
std::string b;
int x;
double y;

std::vector<std::string> split(const std::string& s, char delimiter)
{
   std::vector<std::string> tokens;
   std::string token;
   std::istringstream tokenStream(s);
   while (std::getline(tokenStream, token, delimiter))
   {
      tokens.push_back(token);
   }
   return tokens;
}

int main()
{
    std::string str = "hello,how are you?,3,4";
    std::vector<std::string> vec;
    vec = split(str, ',');

    a = vec[0];
    b = vec[1];
    x = std::stoi(vec[2]);              // support in c++11
    x = atoi(vec[2].c_str());
    y = std::stod(vec[2].c_str());      // support in c++11
    y = atof(vec[2].c_str());

    std::cout << a << "," << b << "," << x << "," << y << std::endl;

}

输出将是:

hello,how are you?,3,3

【讨论】:

  • 这最终成为最有效的方法。我不得不稍微修改一下代码以使其适用于我的应用程序,但 getline(tokenStream, token, delimiter) 是有效的。
猜你喜欢
  • 2014-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多