Int tokenizer

谁说我不能喝 提交于 2019-12-28 11:53:19

问题


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:

list[0]=12

list[1]=34

list[2]=46

In particular, I'm wondering if Boost::Tokenizer does this. Although I couldn't find any examples that didn't use strings.


回答1:


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>());



回答2:


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.




回答3:


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




回答4:


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...



来源:https://stackoverflow.com/questions/1141741/int-tokenizer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!