gpt4 book ai didi

c - 递归删除字符串中的重复字符

转载 作者:行者123 更新时间:2023-12-04 04:12:21 25 4
gpt4 key购买 nike

我正在尝试创建一个递归函数,该函数从字符串中删除连续的重复字符。除了前几个字符外,它工作正常。例如,如果我的输入是 MMMMMuuuuuOOOOOKKKKLLLEE OOOOLLL 或类似这样的内容,则输出是 MMuOKLE OL。正如您所看到的,除了前两个 M,它工作正常。我怎样才能使第一部分也起作用?这是我的代码:

#include <stdio.h>

char* remove_duplicates (char* str){
if(*(str+1)!='\0'){
if(*str==*(str+1)){
*(str+1)=*(str+2);
remove_duplicates(str+1);
}
remove_duplicates(str+1);
}
return str;
}

int main()
{
char sample[] = "MMMMMuuuuuOOOOOKKKKLLLEE OOOOLLL";

printf("OLD: |%s|\n", sample);
printf("NEW: |%s|\n", remove_duplicates(sample));

return 0;
}

最佳答案

给你。

#include <stdio.h>

char * remove_duplicates( char *s )
{
if ( *s )
{
if ( *s == *( s + 1 ) )
{
*( s + 1 ) = *( s + 2 );
remove_duplicates( s + 1 );
remove_duplicates( s );
}
else
{
remove_duplicates( s + 1 );
}
}

return s;
}

int main(void)
{
char s[] = "MMMMMuuuuuOOOOOKKKKLLLEE";

remove_duplicates( s );

puts( s );

return 0;
}

程序输出为

MuOKLE

关于c - 递归删除字符串中的重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61489925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com