Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 将字符串中的重复字符移动到末尾_C_C Strings - Fatal编程技术网

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

C 将字符串中的重复字符移动到末尾,c,c-strings,C,C Strings,我试图将字符串中的重复字符移动到其结束位置,但我的代码对两个以上的重复字符无效。我试图解决它,但没有得到它。 这是我的密码 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); *--

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

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;
}
#包括
#包括
void rep2end(字符*字符串){
字符*s、*p、*e、*stop;
字符c;
s=字符串;
e=s+strlen(字符串)-1;/*查找字符串结尾*/
停止=e;/*停止处理的位置*/
while(stop>s){
c=*s;/*要查找的字符*/
而(*(s+1)=c){/*重复字符*/
对于(p=s+1;*p;p++){/*向左移动以覆盖当前位置*s*/
*(p-1)=*p;
}
*e=c;/*将end char设置为我们刚刚找到的重复*/
停止--;/*向左撞击停止位置以防止重新处理*/
}
s++;
}
}
主要(){
[]中的字符*={“aabbccefghi”、“uglyfruit”、“highbbchair”};
char*out[]={“abcefghiabc”、“uglyfruit”、“highbchairbbb”};
字符串[100];
int i;

对于(i=0;iI输入了100个字符,它崩溃了。:@Daniel我认为它没有崩溃。阅读并改进问题,以包括预期输出和观察到的输出,或者在崩溃的情况下(在问题代码中)(使用调试器),或者在编译器错误的情况下,错误和行(在问题代码中)发生的位置。是否需要在结尾处多次出现的每个字符的第二次和后续出现,或者只是相邻的重复字符?您知道字符串的长度吗?适合短字符串的答案(例如小于100字节)可能不适用于长字符串。此外,请修复缩进(因此,制表符的代码格式比较复杂,最好只使用空格)此外,避免在表达式中使用
+
--
,如
*--p=c;
,除非你能熟练使用c语言,否则很容易出错。