Search code examples
c++stringsplittokentokenize

C++ split string class in function not using strtok()


I have a default constructor function that takes in a string class variable (not char*) and needs to tokenize that string by a delimiter which in my particular case is a comma. Since I am using the string class I cannot within my knowledge use strtok() because it expects a char* as an input and not a string class. Given the code below how can I split the string into smaller strings given that the first two tokens are a string, the third an in and the fourth a 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
}

Solution

  • Try bellow source-code : (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;
    
    }
    

    The output will be :

    hello,how are you?,3,3