用一个字符替换字符串中的多个字符

Replace multiple characters in a string with one char

本文关键字:字符 字符串 替换 一个      更新时间:2023-10-16

用一个字符替换字符串中的多个字符的最佳方法是什么?

string str("1   1     1");
//out: 1 1 1
str.erase(
    std::unique(str.begin(), str.end()),
    str.end());

这不仅仅适用于空格。例如,字符串"aaabbbcccddd"将变成"abcd"。这就是你想要的吗?如果您只想将空格减少为一个空格,则可以将二进制谓词作为第三个参数传递给std::unique,例如:

bool BothAreSpaces(char lhs, char rhs)
{
    return (lhs == ' ') && (rhs == ' ');
}