很多情况下我们需要对字符串进行分割,如:“a,b,c,d”,以‘,’为分隔符进行分割:
stringex.h
#ifndef _STRING_EX_H #define _STRING_EX_H #include <string> #include <vector> // 字符串分割 int StringSplit(std::vector<std::string>& dst, const std::string& src, const std::string& separator); // 去掉前后空格 std::string& StringTrim(std::string &str); #endif
stringex.cpp
#include "stringex.h" int StringSplit(std::vector<std::string>& dst, const std::string& src, const std::string& separator) { if (src.empty() || separator.empty()) return 0; int nCount = 0; std::string temp; size_t pos = 0, offset = 0; // 分割第1~n-1个 while((pos = src.find_first_of(separator, offset)) != std::string::npos) { temp = src.substr(offset, pos - offset); if (temp.length() > 0){ dst.push_back(temp); nCount ++; } offset = pos + 1; } // 分割第n个 temp = src.substr(offset, src.length() - offset); if (temp.length() > 0){ dst.push_back(temp); nCount ++; } return nCount; } std::string& StringTrim(std::string &str) { if (str.empty()){ return str; } str.erase(0, str.find_first_not_of(" ")); str.erase(str.find_last_not_of(" ") + 1); return str; }