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

Ali*_*ani 3 c string

好吧,我正在寻找一个减少' '字符串中多个空格字符的函数.

例如,s给出的字符串:

s="hello__________world____!"
Run Code Online (Sandbox Code Playgroud)

该函数必须返回 "hello_world_!"

在python中我们可以通过regexp简单地完成它:

re.sub("\s+", " ", s);
Run Code Online (Sandbox Code Playgroud)

Ide*_*lic 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;
}
Run Code Online (Sandbox Code Playgroud)