Int tokenizer

后端 未结 4 1562
小蘑菇
小蘑菇 2020-12-08 16:59

I know there are string tokenizers but is there an "int tokenizer"?

For example, I want to split the string "12 34 46" and have:

相关标签:
4条回答
  • 2020-12-08 17:08

    The C++ String Toolkit Library (StrTk) has the following solution to your problem:

    #include <string>
    #include <deque>
    #include "strtk.hpp"
    
    int main()
    { 
       {
          std::string data = "12 34 46";
          std::deque<int> int_list;
          strtk::parse(data," ",int_list);
       }
    
       {
          std::string data = "12.12,34.34|46.46 58.58";
          std::deque<double> double_list;
          strtk::parse(data," ,|",double_list);
       }
    
       return 0;
    }
    

    More examples can be found Here

    Note: The parsing process is EXTREMELY fast and efficient, putting stdlib and boost based solutions to shame.

    0 讨论(0)
  • 2020-12-08 17:09

    Yes there is: use a stream, e.g. a stringstream:

    stringstream sstr("12 34 46");
    int i;
    while (sstr >> i)
        list.push_back(i);
    

    Alternatively, you can also use STL algorithms and/or iterator adapters combined with constructors:

    vector<int> list = vector<int>(istream_iterator<int>(sstr), istream_iterator<int>());
    
    0 讨论(0)
  • 2020-12-08 17:16

    i am not sure if you can do this without using string or char* because you have to but both numbers and spaces into same set...

    0 讨论(0)
  • 2020-12-08 17:22

    What you're looking for is 2 separate actions. First tokenize the string, then convert each token to an int.

    0 讨论(0)
提交回复
热议问题