namespace cutl { /** * @brief The type of vector strings used in this library. * */ using strvec = std::vector<std::string>;
/** * @brief Split a string into a vector of substrings using a given separator. * * @param str the string to be split. * @param separator the separator to split the string. * @return strvec the vector of substrings. */ strvec split(const std::string &str, const std::string &separator);
/** * @brief Join a vector of strings into a single string using a given separator. * * @param strlist the vector of strings to be joined. * @param separator the separator to join the strings. * @return std::string the joined string. */ std::string join(const strvec &strlist, const std::string &separator = ""); } // namespace cutl
std::string join(const strvec &strlist, const std::string &separator) { std::string text; for (size_t i = 0; i < strlist.size(); i++) { text += strlist[i]; if (i < strlist.size() - 1) { text += separator; } }
// split std::string fruits = "apple, banana, orange, pear"; std::cout << "fruits: " << fruits << std::endl; auto fruits_vec = cutl::split(fruits, ","); std::cout << "list fruits item:" << std::endl; for (size_t i = 0; i < fruits_vec.size(); i++) { auto item = fruits_vec[i]; auto fruit = cutl::strip(item); std::cout << item << ", after strip:" << fruit << std::endl; fruits_vec[i] = fruit; } // join std::cout << "join fruits with comma: " << cutl::join(fruits_vec, "; ") << std::endl; }
5. 运行结果
1 2 3 4 5 6 7 8
-------------------------------------------TestJoinSplit-------------------------------------------- fruits: apple, banana, orange, pear list fruits item: apple, after strip:apple banana, after strip:banana orange, after strip:orange pear, after strip:pear join fruits with comma: apple; banana; orange; pear