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

标签 c++ stdstring

在 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/

相关文章:

c++ - 如何在运行时将字符串转换为自身的引用版本?

c++ - 如何获取 std::string 中的字符数?

c++ - 在 C++ 中将字符数组从索引 i 转换为字符串 j

c++ - 并行 for 比顺序 for 慢

c++ - 查找数组中缺失的数字

c++ - 使用 QTcpSocket 发送字节

c++ - 获取 QCheckBox 在 QTableWidget 中的单元格位置

c++ - 格式说明符 C++ 有什么问题

c++ - 是否可以同时使用 C++11 ABI _and_ cxx11 风格和旧式字符串?

C++ 如何从 std::string 中删除\0 字符