本文主要是介绍C++ 字符串处理4-根据指定的分隔符将字符串分割为多个子串根据指定的分隔符将多个子串连接成一个字符串,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1. 关键词
C++ 字符串处理 分割字符串 连接字符串 跨平台
2. strutil.h
#pragma once#include <string>
#include <vector>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
3. strutil.cpp
#include <cctype>
#include <algorithm>
#include "strutil.h"namespace cutl
{strvec split(const std::string &str, const std::string &pattern){strvec res;if (str == "")return res;// 在字符串末尾也加入分隔符,方便截取最后一段std::string strs = str + pattern;size_t pos = strs.find(pattern);int startIndex = 0;while (pos != strs.npos){std::string temp = strs.substr(startIndex, pos - startIndex);res.emplace_back(temp);startIndex = pos + 1;pos = strs.find(pattern, startIndex);}return res;}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;}}return text;}
} // namespace cutl
4. 测试代码
#include "common.hpp"
#include "strutil.h"void TestJoinSplit()
{PrintSubTitle("TestJoinSplit");// splitstd::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;}// joinstd::cout << "join fruits with comma: " << cutl::join(fruits_vec, "; ") << std::endl;
}
5. 运行结果
-------------------------------------------TestJoinSplit--------------------------------------------
fruits: apple, banana, orange, pear
list fruits item:
apple, after strip:applebanana, after strip:bananaorange, after strip:orangepear, after strip:pear
join fruits with comma: apple; banana; orange; pear
6. 源码地址
更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。
这篇关于C++ 字符串处理4-根据指定的分隔符将字符串分割为多个子串根据指定的分隔符将多个子串连接成一个字符串的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!