2013-10-27 172 views
-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); 
} 
+3

我輸入100個字符,它墜毀。 :( –

+0

@丹尼爾我認爲它不會崩潰 – Chetu

+1

閱讀http://sscce.org並改進問題以包括預期輸出和觀察輸出,或者在崩潰的情況下(在問題代碼中)崩潰(使用調試器),或者在編譯器錯誤的情況下,錯誤和行(在問題代碼中)發生的位置 – hyde

回答

0

希望你喜歡的測試代碼

#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; 
} 
相關問題