更改多个空格一个空格的递归形式 [英] recursive form of changing multiple spaces to one space
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/14702016/im-trying-to-make-this-$c$c-recursive-but-for-some-reason-it-doesnt-work\">Im试图让这个code递归,但由于某种原因,它不工作
我试着使用递归更改多个空格一个空格任何人都可以帮忙写程序?
例如,A_ _ _B变为a_b
它是我尝试了很长的时间做任务!谁能帮助?
Im trying to write program using RECURSION to change multiple spaces to one space can anyone help ? example "a___b" changes to "a_b" it is a task that im trying to do for a long time ! can anyone help ?
在这里,我试过,但我认为递归设计不工作
here i tried this but i think the design doesnt work for recursion
void text_r(char *str)
{
char *dst = str;
if(*str=='\0')return ;
*dst++ = *str;
if (isspace(*str)) {
do ++str; while (isspace(*str));
--str;
}
return text_r(str++);
}
我写了code,而不递归,但我在转换问题有它
i wrote the code without recursion but i have problem in converting it
无效COM press_spaces(字符*海峡)
{
字符* DST = str中;
void compress_spaces(char *str) { char *dst = str;
for (; *str; ++str) {
*dst++ = *str;
if (isspace(*str)) {
do ++str; while (isspace(*str));
--str;
}
}
*dst = 0;
}
推荐答案
递归版本(避免任何重复的部分,如,而的)使用相同的指针,作为参数给出两次
Recursive version (avoiding any iterative part, like while) using the same pointer, given twice as argument
void recur(char *str, char *out) {
if (*str!=' ' || str[1]!=' ') *out++ = *str;
if (*str) recur(str+1, out);
}
只有一个参数递归版本
Recursive version having only one param
void recur(char *str) {
static char *out = NULL;
if (out == NULL) out = str;
if (*str!=' ' || str[1]!=' ') *out++ = *str;
if (*str) recur(str+1);
}
迭代版本
void iter(char *str) {
char *out = str;
do {
if (*str!=' ' || str[1]!=' ') *out++ = *str;
} while (*str++);
}
要被称为像
char str[] = " abc d e f ";
// either recursive
recur(str, str);
// or iterative
iter(str);
这篇关于更改多个空格一个空格的递归形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!