面试问题:修剪字符串中的多个连续空格

Uni*_*orn 11 c c++ string

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

input  = "I    Like    StackOverflow a      lot"
output = "I Like StackOverflow a lot"
Run Code Online (Sandbox Code Playgroud)

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

Cub*_*bbi 14

使用是否<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';
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这是一个非常好的滥用! (3认同)
  • @Matthieu:我不会称之为滥用 - "unique"stl算法正是针对这种情况而设计的.要求一个仿函数类无疑是尴尬的,但这是对C++ 0X之前的stl算法的一个相当普遍的限制. (3认同)

dec*_*ype 11

一个c ++ 0x - 使用lambda而不是常规函数对象的解决方案.与Cubbi的解决方案相比.

#include <string>
#include <algorithm>

int main()
{
    std::string str = "I    Like    StackOverflow a      lot";

    str.erase(std::unique(str.begin(), str.end(),
      [](char a, char b) { return a == ' ' && b == ' '; } ), str.end() );  
}
Run Code Online (Sandbox Code Playgroud)

  • 而不是 `a == ' '` 可以使用 `isspace(a)` 来更加一致。 (2认同)

Meh*_*dad 10

保留两个索引:下一个可用的字母(例如i),以及您正在检查的当前索引(例如j).

只需循环遍历所有字符j,每当看到一个字母时,将其复制到索引i,然后递增i.如果您看到空格前面没有空格,也请复制空格.

认为这可以就地工作......


Ecl*_*pse 6

我只想这样做:

int main(int argc, char* argv[])
{
    char *f, *b, arr[] = "  This        is    a test.                ";
    f = b = arr;

    if (f) do
    {
        while(*f == ' ' && *(f+1) == ' ') f++;
    } while (*b++ = *f++);

    printf("%s", arr);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • @VJo,它打印一个空字符串.它还会打印什么? (2认同)