我正在使用以下代码解析C++中的字符串:
using namespace std;
string parsed,input="text to be parsed";
stringstream input_stringstream(input);
if (getline(input_stringstream,parsed,' '))
{
// do some processing.
}
使用单个字符分隔符进行解析就可以了。但是如果我想使用一个字符串作为分隔符呢?
示例:我想拆分:
scott>=tiger
使用>=
作为分隔符,这样我就可以获取scott和tiger。
发布于 2013-01-11 05:20:23
此方法使用std::string::find
,而不会通过记住前一个子字符串标记的开头和结尾而改变原始字符串。
#include <iostream>
#include <string>
int main()
{
std::string s = "scott>=tiger";
std::string delim = ">=";
auto start = 0U;
auto end = s.find(delim);
while (end != std::string::npos)
{
std::cout << s.substr(start, end - start) << std::endl;
start = end + delim.length();
end = s.find(delim, start);
}
std::cout << s.substr(start, end);
}
发布于 2016-05-26 15:25:41
您可以使用next函数拆分字符串:
vector<string> split(const string& str, const string& delim)
{
vector<string> tokens;
size_t prev = 0, pos = 0;
do
{
pos = str.find(delim, prev);
if (pos == string::npos) pos = str.length();
string token = str.substr(prev, pos-prev);
if (!token.empty()) tokens.push_back(token);
prev = pos + delim.length();
}
while (pos < str.length() && prev < str.length());
return tokens;
}
发布于 2020-11-18 11:46:16
您还可以使用正则表达式来执行以下操作:
std::vector<std::string> split(const std::string str, const std::string regex_str)
{
std::regex regexz(regex_str);
std::vector<std::string> list(std::sregex_token_iterator(str.begin(), str.end(), regexz, -1),
std::sregex_token_iterator());
return list;
}
相当于:
std::vector<std::string> split(const std::string str, const std::string regex_str)
{
std::sregex_token_iterator token_iter(str.begin(), str.end(), regexz, -1);
std::sregex_token_iterator end;
std::vector<std::string> list;
while (token_iter != end)
{
list.emplace_back(*token_iter++);
}
return list;
}
并像这样使用它:
#include <iostream>
#include <string>
#include <regex>
std::vector<std::string> split(const std::string str, const std::string regex_str)
{ // a yet more concise form!
return { std::sregex_token_iterator(str.begin(), str.end(), std::regex(regex_str), -1), std::sregex_token_iterator() };
}
int main()
{
std::string input_str = "lets split this";
std::string regex_str = " ";
auto tokens = split(input_str, regex_str);
for (auto& item: tokens)
{
std::cout<<item <<std::endl;
}
}
在线玩吧!http://cpp.sh/9sumb
您可以简单地使用子字符串、字符等,就像normal一样,或者使用实际的正则表达式进行拆分。
它也是简洁和C++11的!
https://stackoverflow.com/questions/14265581
复制相似问题