split function for C++

人盡茶涼 提交于 2019-12-10 17:40:38

问题


Is there a split type function for C++ similar to Java? I know of ignore, but I don't quite understand it, and how it'll work for my case.

My input is:

{
  item = ball
  book = lord of the rings
  movie = star wars
}

My input given is an <attribute> = <value> and I have to store the two in different strings, or integers (depending on the value, for example, if its a number, use an integer).


回答1:


Use Boost::tokenizer as it does what you want to do. From the manual:

// simple_example_1.cpp
#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>

int main(){
   using namespace std;
   using namespace boost;
   string s = "This is,  a test";
   tokenizer<> tok(s);
   for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg){
       cout << *beg << "\n";
   }
}



回答2:


Use strtok(): http://www.cplusplus.com/reference/clibrary/cstring/strtok/.

Just know that its not re-entrant because it uses an internal static variable, so don't call it twice in nested loops or anything like that.

and EDIT:

This is a very cool SO solution that would tokenize the whole string by spaces - you'd have to process the values back together after the = but it would teach you STL well :)

Split a string in C++?



来源:https://stackoverflow.com/questions/7583090/split-function-for-c

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