很多情况下我们需要对字符串进行分割,如:“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; }
本文介绍了一种在C++中实现字符串分割的方法,并提供了一个去除字符串前后空格的实用函数。通过具体的代码实现,读者可以了解到如何高效地处理字符串,这对于日常编程工作非常有用。
&spm=1001.2101.3001.5002&articleId=97697097&d=1&t=3&u=9b06ce9f3c204b6aa709e62ee990f20d)

被折叠的 条评论
为什么被折叠?



