由于这是c++分割字符串或类似的顶级Stack Overflow谷歌搜索结果,我将发布一个完整的、复制/粘贴可运行的示例,展示这两种方法。
splitString使用stringstream(在大多数情况下可能是更好更简单的选项)
splitString2使用find和substr(一种更手动的方法)
// SplitString.cpp
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
// function prototypes
std::vector<std::string> splitString(const std::string& str, char delim);
std::vector<std::string> splitString2(const std::string& str, char delim);
std::string getSubstring(const std::string& str, int leftIdx, int rightIdx);
int main(void)
{
// Test cases - all will pass
std::string str = "ab,cd,ef";
//std::string str = "abcdef";
//std::string str = "";
//std::string str = ",cd,ef";
//std::string str = "ab,cd,"; // behavior of splitString and splitString2 is different for this final case only, if this case matters to you choose which one you need as applicable
std::vector<std::string> tokens = splitString(str, ',');
std::cout << "tokens: " << "\n";
if (tokens.empty())
{
std::cout << "(tokens is empty)" << "\n";
}
else
{
for (auto& token : tokens)
{
if (token == "") std::cout << "(empty string)" << "\n";
else std::cout << token << "\n";
}
}
return 0;
}
std::vector<std::string> splitString(const std::string& str, char delim)
{
std::vector<std::string> tokens;
if (str == "") return tokens;
std::string currentToken;
std::stringstream ss(str);
while (std::getline(ss, currentToken, delim))
{
tokens.push_back(currentToken);
}
return tokens;
}
std::vector<std::string> splitString2(const std::string& str, char delim)
{
std::vector<std::string> tokens;
if (str == "") return tokens;
int leftIdx = 0;
int delimIdx = str.find(delim);
int rightIdx;
while (delimIdx != std::string::npos)
{
rightIdx = delimIdx - 1;
std::string token = getSubstring(str, leftIdx, rightIdx);
tokens.push_back(token);
// prep for next time around
leftIdx = delimIdx + 1;
delimIdx = str.find(delim, delimIdx + 1);
}
rightIdx = str.size() - 1;
std::string token = getSubstring(str, leftIdx, rightIdx);
tokens.push_back(token);
return tokens;
}
std::string getSubstring(const std::string& str, int leftIdx, int rightIdx)
{
return str.substr(leftIdx, rightIdx - leftIdx + 1);
}