将字符串拆分为数组(C++)

Split a string into an array in C++

本文关键字:C++ 数组 字符串 拆分      更新时间:2023-10-16

可能的重复项:
如何在C++中拆分字符串?

我有一个数据输入文件,每一行都是一个条目。 在每一行中,每个"字段"都由空格分隔" "所以我需要按空格拆分行。其他语言有一个名为split的函数(C#,PHP等(,但我找不到C++的函数。我怎样才能做到这一点?这是我的代码,它得到了这些行:

string line;
ifstream in(file);
while(getline(in, line)){
  // Here I would like to split each line and put them into an array
}
#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!
}

顺便说一下,像我一样使用限定名称,例如 std::getlinestd::ifstream。您似乎在代码中的某处编写了using namespace std,这被认为是一种不好的做法。所以不要那样做:

  • 为什么"使用命名空间 std"被认为是不好的做法?
vector<string> v;
boost::split(v, line, ::isspace);

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

我已经为我的类似需求编写了一个函数,也许你可以使用它!

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;
}

尝试strtok .在C++参考中查找它:。

下面的代码使用 strtok() 将字符串拆分为标记,并将标记存储在向量中。

#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[]   = " ,tn";
char *token;

int main()
{
   vector<string> vec_String_Lines;
   token = strtok( one_line_string, seps );
   cout << "Extracting and storing data in a vector..nnn";
   while( token != NULL )
   {
      vec_String_Lines.push_back(token);
      token = strtok( NULL, seps );
   }
     cout << "Displaying end result in  vector line storage..nn";
    for ( int i = 0; i < vec_String_Lines.size(); ++i)
    cout << vec_String_Lines[i] << "n";
    cout << "nnn";

return 0;
}

C++最好与几乎标准的库提升一起使用。

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

要么使用 stringstream,要么从ifstream中逐个令牌读取。

要使用字符串流执行此操作:

string line, token;
ifstream in(file);
while(getline(in, line))
{
    stringstream s(line);
    while (s >> token)
    {
        // save token to your array by value
    }
}