binapi
binapi copied to clipboard
tools.cpp - split_string function didn't not cover some situations
/*!
* 它接受一个std::string类型的字符串str和一个指向C风格字符串的指针sep作为参数。
* 函数的目的是将str字符串按照sep指定的分隔符进行分割,并将分割后的子字符串存储在一个std::vector<std::string>中。
* @param str: 待分割的字符串
* @param sep: 分隔符
* @return: 分隔之后的vector字符串
*/
std::vector<std::string> split_string(const std::string &str, const char *sep) {
std::vector<std::string> res{};
boost::algorithm::split(res, str, boost::is_any_of(sep));
for ( auto &it: res ) {
boost::algorithm::trim(it);
}
// 去除空字符串
// res.erase(std::remove(res.begin(), res.end(), ""), res.end());
return res;
}
for example, test some situation:
TEST_F(ToolsTestSplitString, s3){
// 测试使用多个字符作为分隔符
std::string str = "apple::banana::cherry::date";
const char *sep = "::";
std::vector<std::string> expected = {"apple", "banana", "cherry", "date"};
std::vector<std::string> result = split_string(str, sep);
EXPECT_EQ(expected, result);
}
it will not generate the expected std::vectorstd::string, because some element is "", so maybe it is better to add a code to remove "".
res.erase(std::remove(res.begin(), res.end(), ""), res.end());