替换字符串C++标点符号

Replace punctuation in C++ string

本文关键字:标点符号 C++ 字符串 替换      更新时间:2023-10-16

我试图理解为什么binary_search((找不到某些标点字符,而find((却找到了:

array<char, 25> punctuation_chars{''', '"', ',', '.', ';', ':', '+', '*', '-', '_', '?', '!', '=', '|', '^', '/', '', '(', ')', '[', ']', '{', '}', '<', '>'};
bool is_punctuation(char c)
{
    auto ret = find(cbegin(punctuation_chars), cend(punctuation_chars), c) != cend(punctuation_chars);
    // auto ret = binary_search(cbegin(punctuation_chars), cend(punctuation_chars), c);
    if (c == ',')
        cout << c << " is" << (ret ? "" : " not") << " punctuation" << endl;
    return ret;
}

注释行不起作用(例如,对于 c == ',' 返回 false(,而查找返回 cend(punctuation_chars(...

punctuation_chars没有

排序,因此std::binary_search不起作用。您需要致电std::sort

std::sort(std::begin(punctuation_chars), std::end(punctuation_chars));