我有一系列存储在单个数组中的字符串,由空值分隔(例如,'f','o','o','\0','b','a','r','\0'...),我需要将其拆分为std::vector<std::string>
或类似的值。
我可以使用std::find
或strlen
编写一个10行的循环来完成这项工作(实际上我刚刚就做到了),但我想知道是否有更简单/更优雅的方法来完成这项工作,例如我忽略的一些STL算法,它可以被诱使这样做。
这是一个相当简单的任务,如果有一些聪明的STL技巧可以使它变得更简单,我也不会感到惊讶。
有谁愿意接受吗?
发布于 2011-08-30 21:20:18
我的两点意见:
const char* p = str;
std::vector<std::string> vector;
do {
vector.push_back(std::string(p));
p += vector.back().size() + 1;
} while ( // whatever condition applies );
发布于 2011-08-30 21:18:44
Boost解决方案:
#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
//input_array must be a Range containing the input.
boost::split(
strs,
input_array,
boost::is_any_of(boost::as_array("\0")));
发布于 2011-08-30 22:02:58
下面的代码依赖于具有隐式构造函数的std::string
,该构造函数接受const char*
,从而使循环成为非常简单的两行代码:
#include <iostream>
#include <string>
#include <vector>
template< std::size_t N >
std::vector<std::string> split_buffer(const char (&buf)[N])
{
std::vector<std::string> result;
for(const char* p=buf; p!=buf+sizeof(buf); p+=result.back().size()+1)
result.push_back(p);
return result;
}
int main()
{
std::vector<std::string> test = split_buffer("wrgl\0brgl\0frgl\0srgl\0zrgl");
for (auto it = test.begin(); it != test.end(); ++it)
std::cout << '"' << *it << "\"\n";
return 0;
}
这个解决方案假设缓冲区的大小是已知的,并且字符串列表的结尾条件是已知的。如果列表由"\0\0"
终止,则需要将循环中的条件从p!=foo+sizeof(foo)
更改为*p
。
https://stackoverflow.com/questions/7243723
复制相似问题