在C++中将字符串拆分为数组

15

可能是重复问题:
如何在C++中分割字符串?

我有一个数据输入文件,每行都是一个条目。在每行中,每个 "字段" 都由一个空格 " " 分隔,所以我需要通过空格拆分行。其他语言(例如 C#、PHP 等)都有一个称为 split 的函数,但我找不到 C++ 中的这个函数。我该如何实现呢?下面是获取行的代码:

string line;
ifstream in(file);

while(getline(in, line)){

  // Here I would like to split each line and put them into an array

}
7个回答

23
#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,这被认为是一个不好的做法。所以不要这样做:


你能提供一个讨论链接,解释为什么使用 using namespace x 是一种不好的做法吗? - jli
@jli:在我的回答中添加了链接。请查看。 - Nawaz
2
@Nawaz 谢谢,看着我的其他问题,我使用的语法和我在大学里从我的教师那里学习C++的方式是非常值得质疑的 :S!!!!! - Ahoura Ghotbi

6

5
我已经为类似的需求编写了一个函数,也许你可以使用它!
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;
}

3

尝试使用strtok。在C++参考中查找:


3
strtok 是C语言库中的函数,而发帖者询问如何在C++中正确地执行它。 - jli
2
C++不是C吗?(...天哪,所有这些年他们都骗了我:D)。自从什么时候C库在C++中停止工作(或变得不正确)? - LucianMLI
如果混合它们,你会增加不必要的依赖关系,以及其他问题。 - jli
请提供一个链接,涉及在C++中使用C语言时所涉及的问题和依赖项。我是指所有那些错误地编译和在C++中使用C代码和库的年份。 - LucianMLI
我猜依赖关系不是问题,但在我的看法中,这样做 #include <iostream> #include <cstdio> 会变得冗余。 - jli
我刚刚意识到在我的第二个评论中我拼错了dependencies(该死的手机软键盘)。 - jli

1
下面的代码使用 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[]   = " ,\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;
}

0

0

可以使用stringstream或从ifstream中逐个读取标记。

使用stringstream进行操作:

string line, token;
ifstream in(file);

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

当然,如果你愿意的话,你可以使用boost或另一个STL函数来从stringstream中进行复制。 - jli
如果输入以空格结尾,这个内部 while 循环会在末尾生成一个额外的空令牌。惯用的 C++ while(s >> token) 则不会这样做。 - Cubbi
这是正确的。最好编辑以使用那种方法。 - jli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接