我如何用一个空格代替多个空格? [英] How do I replace multiple spaces with a single space?
本文介绍了我如何用一个空格代替多个空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗯,我正在寻找减少字符串中的多个空格字符的功能。
例如字符串取值
给出:
s =你好__________ world____!
函数必须返回参考hello world _!
在Python中,我们可以通过正则表达式这样做只是为:
应用re.sub(\\ S +,,S);
解决方案
这就地修改字符串,在副本上运行它,如果原来的必须是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;
}
这篇关于我如何用一个空格代替多个空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文