gpt4 book ai didi

c - 将字符串中重复的字符移动到末尾

转载 作者:行者123 更新时间:2023-11-30 19:48:18 25 4
gpt4 key购买 nike

我尝试将字符串中的重复字符移动到其结束位置,但我的代码不适用于两个以上的重复字符。我试图解决它但没有得到它。这是我的代码

main () {
char string[100];
char *s, *p;
char c;
scanf("%s", string);
s = string;
c = *s++;
while (*s){
if(*s == c){
for(p = s; *p ; p++)
*p = *(p + 1);
*--p = c;
}
c = *s;
s++;
}
printf ( "%s\n", string);
}

最佳答案

希望您喜欢测试代码

#include <string.h>
#include <stdio.h>


void rep2end(char *string) {
char *s, *p, *e, *stop;
char c;
s = string;
e = s+strlen(string)-1; /* find end of string */
stop = e; /* place to stop processing */
while (stop > s){
c = *s; /* char to look for */
while(*(s+1) == c){ /* repeated char */
for(p = s+1; *p ; p++){ /* shuffle left to overwrite current pos *s */
*(p-1) = *p;
}
*e = c; /* set end char to be the repeat we just found */
stop--; /* bump the stop position left to prevent reprocessing */
}
s++;
}
}


main () {
char *in[]={"aabbccefghi", "uglyfruit", "highbbbbchair"};
char *out[]={"abcefghiabc", "uglyfruit", "highbchairbbb"};
char string[100];
int i;

for (i=0; i<3; i++) {
strcpy(string, in[i]);
rep2end(string);
if (!strcmp(string,out[i])) {
printf("ok\n");
}else {
printf("fail %s should be %s\n", string, out[i]);
}


}
return 0;
}

关于c - 将字符串中重复的字符移动到末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19621492/

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