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

时间:2019-06-17 22:56:13

标签: c++ string stl

我试图了解为什么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),而find返回cend(punctuation_chars)...

1 个答案:

答案 0 :(得分:2)

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

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