Split a string into an array in C++ [duplicate]

独自空忆成欢 提交于 2019-11-30 04:59:52
Nawaz
#include <sstream>  //for std::istringstream
#include <iterator> //for std::istream_iterator
#include <vector>   //for std::vector

while(std::getline(in, line))
{
    std::istringstream ss(line);
    std::istream_iterator<std::string> begin(ss), end;

    //putting all the tokens in the vector
    std::vector<std::string> arrayTokens(begin, end); 

    //arrayTokens is containing all the tokens - use it!
}

By the way, use qualified-names such as std::getline, std::ifstream like I did. It seems you've written using namespace std somewhere in your code which is considered a bad practice. So don't do that:

vector<string> v;
boost::split(v, line, ::isspace);

http://www.boost.org/doc/libs/1_48_0/doc/html/string_algo/usage.html#id3115768

LucianMLI

Try strtok. Look for it in the C++ reference:.

Vijay

I have written a function for a similar requirement of mine, maybe you can use it!

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) 
{
    std::stringstream ss(s+' ');
    std::string item;
    while(std::getline(ss, item, delim)) 
    {
        elems.push_back(item);
    }
    return elems;
}

The code below uses strtok() to split a string into tokens and stores the tokens in a vector.

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

using namespace std;


char one_line_string[] = "hello hi how are you nice weather we are having ok then bye";
char seps[]   = " ,\t\n";
char *token;



int main()
{
   vector<string> vec_String_Lines;
   token = strtok( one_line_string, seps );

   cout << "Extracting and storing data in a vector..\n\n\n";

   while( token != NULL )
   {
      vec_String_Lines.push_back(token);
      token = strtok( NULL, seps );
   }
     cout << "Displaying end result in  vector line storage..\n\n";

    for ( int i = 0; i < vec_String_Lines.size(); ++i)
    cout << vec_String_Lines[i] << "\n";
    cout << "\n\n\n";


return 0;
}
Tristram Gräbener

C++ is best used with the almost-standard-library boost.

And an example : http://www.boost.org/doc/libs/1_48_0/doc/html/string_algo/usage.html#id3115768

Either use a stringstream or read token by token from your ifstream.

To do it with a stringstream:

string line, token;
ifstream in(file);

while(getline(in, line))
{
    stringstream s(line);
    while (s >> token)
    {
        // save token to your array by value
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!