c++ - 面试题: Trim multiple consecutive spaces from a string

标签 c++ c string

这是一道面试题 寻找从字符串中修剪多个空格的最佳解决方案。这个操作应该是就地操作。

input  = "I    Like    StackOverflow a      lot"
output = "I Like StackOverflow a lot"

不允许使用字符串函数,因为这是一道面试题。寻找问题的算法解决方案。

最佳答案

是否使用 <algorithm>是否符合“算法解决方案”?

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
struct BothAre
{
    char c;
    BothAre(char r) : c(r) {}
    bool operator()(char l, char r) const
    {
            return r == c && l == c;
    }
};
int main()
{
    std::string str = "I    Like    StackOverflow a      lot";
    std::string::iterator i = unique(str.begin(), str.end(), BothAre(' '));
    std::copy(str.begin(), i, std::ostream_iterator<char>(std::cout, ""));
    std::cout << '\n';
}

测试运行:https://ideone.com/ITqxB

关于c++ - 面试题: Trim multiple consecutive spaces from a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5561138/

相关文章:

c++ - 如何在 Win32 中使用对话框资源?

c++ - 文件读取停止

c - 在共享库中获取 undefined reference

python - 用字符串数组替换字符串

c++ - 为什么 C++ 编译器在这种特殊情况下需要 "typename"关键字?

c++ - 使用 "memberspace"成语?

c++ - 跨 C API 边界将句柄传递给 C++ 类

c - 将省略号传递给另一个可变参数函数

python - MySQL python : Cursor returns the variable name

regex - Bash 用变量替换字符串中的第 N 个单词