gpt4 book ai didi

C++ 具有多个字符的多个定界符

转载 作者:太空宇宙 更新时间:2023-11-04 13:34:17 24 4
gpt4 key购买 nike

在 C++ 中,我在使用单个字符定界符和字符串定界符(例如“<=”作为定界符而不是“=”)编写多个定界符时遇到了问题。下面的代码使用单个字符定界符(我将定界符设置为空格、逗号、点、加号和等号)并很好地分隔字符串行中的单词。但是,我不知道如何向这段代码添加字符串定界符。

std::string delimiters = " ,.+=";//I want "<=" added as a single delimiter
std::string line = "this+is,a.string=testing one";
std::size_t prev = 0, pos;
while ((pos = line.find_first_of(delimiters, prev)) != std::string::npos)
{
if (pos > prev)
{
cout << line.substr(prev, pos-prev) << endl;
prev = pos + 1;
}
}
if (prev < line.length()){
cout << line.substr(prev, std::string::npos) << endl;
}

最佳答案

这是一种方法,您可以通过删除从 line_copy 字符串中找到的定界符来完成此操作,并为特殊定界符使用特殊的 if 语句。满example here :

auto pos = find_first_of(begin(line_copy), end(line_copy), begin(delimiters), 
end(delimiters));

while (pos != line_copy.end()) {
if (pos != line_copy.end()) {
if (*pos == '<' && *(pos + 1) == '=') {
cout << "delimiter: \'";
cout << string(pos, pos + 2) << "\'" << endl;

// remove the delimiters from copy string
line_copy.erase(pos, pos + 2);
}
else {
cout << "delimiter: \'" << *pos << "\'" << endl;

// remove the delimiters from copy string
line_copy.erase(pos, pos + 1);
}
}
cout << endl;

pos = find_first_of(begin(line_copy), end(line_copy), begin(delimiters),
end(delimiters));
}

关于C++ 具有多个字符的多个定界符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30230248/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com