且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何用一个空格代替多个空格?

更新时间:2023-02-23 10:36:37

这就地修改字符串,在副本上运行它,如果原来的必须是preserved一个版本:

 无效COM press_spaces(字符*海峡)
{
    字符* DST = str中;    对于(*海峡;海峡++){
        * DST ++ = *海峡;        如果(isspace为(* STR)){
            做++海峡;            而(isspace为(* STR));            --str;
        }
    }    * DST = 0;
}

Well I'm looking for a function that reduce multiple space characters ' ' in a string.

For example for string s given :

s="hello__________world____!"

The function must return "hello_world_!"

In python we can do it via regexp simply as:

re.sub("\s+", " ", s);

A version that modifies the string in place, run it on a copy if the original must be preserved:

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

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

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

            while (isspace(*str));

            --str;
        }
    }

    *dst = 0;
}