面试问题:从一个字符串中删除多个连续空格

Interview Question : Trim multiple consecutive spaces from a string

本文关键字:字符串 删除 空格 连续 一个 问题 面试      更新时间:2023-10-16

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

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

使用lambda而不是常规函数对象的c++0x解决方案。与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() );  
}

保留两个索引:下一个可放入字母的位置(例如i(和当前正在检查的索引(例如j(。

只需使用j循环所有字符,每当您看到一个字母时,将其复制到索引i,然后递增i。如果看到前面没有空格的空格,也可以复制该空格。

认为这会起作用。。。

我会选择这个:

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;
}

我提出了一个小的状态机(只是一个简单的switch语句(。因为如果面试官和我一样,他们会要求你做的第一个改进是完全修剪任何前导或尾随空格,这样:

"    leading and    trailing    "

转换为:

"leading and trailing"

而不是:

" leading and trailing "

这是对状态机设计的一个非常简单的修改,对我来说,在"直接"编码循环上理解状态机逻辑似乎更容易,即使它比直接循环多需要几行代码。

如果你认为对直接循环的修改不会太糟糕(这是可以合理论证的(,那么我(作为面试官(会说,我也希望去掉数字中的前导零。

另一方面,很多面试官实际上可能不喜欢状态机解决方案,认为它是"非最优的"。我想这取决于你试图优化什么。

这里它只使用stdio:

#include <stdio.h>
int main(void){
    char str[] = "I    Like    StackOverflow a      lot";
    int i, j = 0, lastSpace = 0;
    for(i = 0;str[i]; i++){
        if(!lastSpace || str[i] != ' '){
            str[j] = str[i];
            j++;
        }
        lastSpace = (str[i] == ' ');
    }
    str[j] = 0;
    puts(str);
    return 0;
}
修剪多个空格也意味着一个空格后面应该总是跟一个非空格字符。
int pack = 0;
char str[] = "I    Like    StackOverflow a      lot";
for (int iter = 1; iter < strlen(str); iter++)
{
    if (str[pack] == ' ' && str[iter] == ' ')
        continue;
    str[++pack] = str[iter];
}
str[++pack] = NULL;
int j = 0;
int k=0;
char str[] = "I    Like    StackOverflow a      lot"; 
int length = strlen(str);
char str2[38];
for (int i = 0; i < length; i++) 
{ 
    if (str[i] == ' ' && str[i+1] == ' ') 
     continue; 
    str2[j] = str[i];
    j++;
} 
str2[j] =NULL;
cout<<str2;
void trimspaces(char * str){
    int i = 0;
    while(str[i]!=''){
        if(str[i]==' '){
            for(int j = i + 1; j<strlen(str);j++){
                if(str[j]!=' '){
                    memmove(str + i + 1, str + j, strlen(str)-j+1);
                    break;
                }
            }
        }
        i++;
    }
}

Haskell:中的功能变体

import Data.List (intercalate)
trimSpaces :: String -> String
trimSpaces =  intercalate " " . words

算法下一篇:

  1. 将字符串分解为用空格分隔的单词列表
  2. 连接列表在列表中的每个元素之间插入一个空格

这是一个非常简单的去除多余空白的实现。

#include <iostream>
std::string trimExtraWhiteSpaces(std::string &str);
int main(){
    std::string str = "  Apple    is a     fruit  and I like     it   .  ";
    str = trimExtraWhiteSpaces(str);
    std::cout<<str;
}
std::string trimExtraWhiteSpaces(std::string &str){
    std::string s;
    bool first = true;
    bool space = false;
    std::string::iterator iter;
    for(iter = str.begin(); iter != str.end(); ++iter){
        if(*iter == ' '){
            if(first == false){
                space = true;
            }
        }else{
            if(*iter != ',' && *iter != '.'){
                if(space){
                    s.push_back(' ');
                }
            }
            s.push_back(*iter);
            space = false;
            first = false;
        }
    }
    return s;
}
std::string tripString(std::string str) {
    std::string result = "";
    unsigned previous = 0;
    if (str[0] != ' ')
        result += str[0];
    for (unsigned i = 1; i < str.length()-1; i++) {
        if (str[i] == ' ' && str[previous] != ' ')
            result += ' ';
        else if (str[i] != ' ')
            result += str[i];
        previous++;
    }
    if (str[str.length()-1] != ' ')
        result += str[str.length()-1];
    return result;
}

这可以是CCD_ 7。