将字符串拆分为数组(C++)
Split a string into an array in C++
可能的重复项:
如何在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::getline
,std::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
}
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '