如何用单个空格替换多个空格?

3

我希望您能提供一个函数,用于在字符串中减少多个空格字符' '

例如,对于给定的字符串s

s="hello__________world____!"

该函数必须返回"hello_world_!"。 在Python中,我们可以简单地通过正则表达式来实现:
re.sub("\s+", " ", s);

1
展示一下你目前尝试过的内容。 - Sinan Ünür
你到目前为止做了什么来尝试解决这个问题? - Adam Batkin
我想到一个可以减少多个空格的函数,但它不起作用,可能是递归问题。 - Ali Mezgani
6个回答

8

如果需要保留原始字符串,请在副本上运行修改字符串的版本:

void compress_spaces(char *str)
{
    char *dst = str;

    for (; *str; ++str) {
        *dst++ = *str;

        if (isspace(*str)) {
            do ++str; 

            while (isspace(*str));

            --str;
        }
    }

    *dst = 0;
}

我已经执行了这个函数,但如果我插入“Empty somehow”,我将收到0输出!我认为这不是它应该做的事情... - Oliver
在你的输入上对我有效。我不明白你所说的“接收0输出”的意思。我认为你是错的。;-) - Idelic
当我编译这个语句并输入一个 char* 时,它会删除所有元素,我的输入是 " Empty somehow ",结果是 "",所以是完全空的。如果您告诉我我做错了什么,我会很高兴的 :-) - Oliver
@Idelic,你为什么要使用++str呢?在这种情况下它和str++一样吗? - srchulo

4

在C标准库中没有这样的函数。必须编写一个函数来完成此操作或使用第三方库。

下面的函数应该可以解决问题。将源字符串用作目标指针以执行原地操作。否则,请确保目标缓冲区具有足够的大小。

void
simplifyWhitespace(char * dst, const char * src)
{
    for (; *src; ++dst, ++src) {
        *dst = *src;
        if (isspace(*src))
            while (isspace(*(src + 1)))
                ++src;
    }

    *dst = '\0';
}

2
void remove_more_than_one_space(char *dest, char *src)
{
    int i, y;
    assert(dest && src);
    for(i=0, y=0; src[i] != '\0'; i++, y++) {
        if(src[i] == ' ' && src[i+1] == ' ') {
            /* let's skip this copy and reduce the y index*/
            y--;
            continue;
        }
        /* copy normally */
        dest[y] = src[i];
    }
    dest[y] = '\0';
}
int main()
{
    char src[] = "Hello   World   ! !!   !";
    char dest[strlen(src) + 1];
    remove_more_than_one_space(dest, src);

    printf("%s\n", dest);
}

我刚刚制作了这个,希望能有所帮助。


但是调用者需要确保dest指向的块比strlen(src)大,否则这将破坏内存。 - Stephen C
为什么要更大?目标(dest)必须至少与源(src)的大小相同。 - Luca Matteis
@Luca:如果确保长度至少为strlen(src),那么你的代码为什么会写成char dest[strlen(src) + 1];呢?;) - Sean
已经成功了。该函数返回一个修剪过的字符串,但末尾带有一个特殊字符。 - Ali Mezgani
@mezgani:我解决了这个问题,我在迭代空字符后添加了1,但实际上并不需要。 - Luca Matteis

1
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int main()
{
    char word[100];
    gets(word);
    //the word has more than a single space in between the words
    int i=0,l,j;
    l=strlen(word);
    for (i=0;i<l;i++)
    {
        if(word[i]==' '&&word[i+1]==' ')
        {
            for(j=i+1;j<l;j++)
            word[j]=word[j+1];
        }
    }
    puts(word);
    return 0;
}

这段代码非常简单,对我来说运行得很好。我不知道这段代码是否会有其他问题,但目前为止它可以正常工作。

0

我正在学习C语言,所以我使用更基础的代码。我正在阅读《C程序设计语言》的第一章,并尝试找到其中一个任务的答案。

这是我想出来的:

#include <stdio.h>

int main()
{
    /* Set two integers:
       c is the character being assessed,
       lastspace is 1 if the lastcharacter was a space*/
    int c, lastspace;
    lastspace = 0;

    /* This while loop will exit if the character is EOF

       The first "If block" is true if the character is not a space,
       and just prints the character
       It also tells us that the lastcharacter was not a space

       The else block will run if the character is a space

       Then the second IF block will run if the last character
       was not also a space (and will print just one space) */

    while((c = getchar()) != EOF){
        if (c != ' '){
            putchar(c);
            lastspace = 0;
        }
        else {
            if (lastspace != 1)
                    putchar(c);
            lastspace = 1;
        }
    }

    return 0;
}

希望这有所帮助! 此外,我很清楚这段代码可能没有优化,但对于像我这样的初学者来说应该很简单易懂! 谢谢,Phil

0

另一种做法是仅打印第一个空格出现直到下一个字符出现,这里是我的暴力解决方案。

#include<stdio.h>
typedef int bool;
#define True  1
#define False 0
int main()
{
        int t;
        bool flag = False;

        while ((t = getchar()) != EOF)
                if (t == ' ' && !flag)
                {
                        putchar(' ');
                        flag = True; // flag is true for the first occurence of space
                }

                else if(t == ' '&& flag)
                        continue;
                else
                {
                        putchar(t);
                        flag = False;
                }

        return 0;
}

希望能有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接