2016-11-30 60 views
0

在文本文件中,我有「abbcccdddd」。我想將「abcd」存儲在一個數組中。C刪除char數組中的重複字符

之前:TX [0] = A,TX [1] = B,TX [3] = C,TX [6] = d

後:TX [0] = A,TX [1] = b,TX [2] = C,TX [3] = d

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

void main() 
{ 
    FILE *fp = fopen("D:\\C#\\Zip\\Text001.txt", "r"); 
    char x; 
    int size; 
    int j, k; 
    int i = 0; 

    fseek(fp, 0, SEEK_END); 
    size = ftell(fp); 
    fseek(fp, 0, SEEK_SET); 
    char tx[size]; 
    x = fgetc(fp); 

    while (x != EOF) 
    { 
     tx[i] = x; 
     printf("%c", tx[i]); 
     x = fgetc(fp); 
     i++; 
    } 
} 
+2

爲什麼輸出ABC,而不是ABCD? – GoodDeeds

+1

你的嘗試似乎根本沒有任何嘗試。它只是讀取文件中的數據。這會讓你看到你描述的*起點。 –

+2

當您從文件中讀取字符時,重複刪除會更容易,因此數組永遠不會重複運行重複字符。你可以通過對你已有的東西進行一些小修改來完成。 –

回答

1

remove_repeatation()將這樣做。

void remove_repeatation(char *str) 
{ 
    char flag[256] = {0}; //Assuming sizeof char is 8. So max 256 different characters. 
    int i   = 0; 
    int j   = 0; 

    for(i=0; str[i] != '\0';) 
    { 
     if(0 == flag[str[i]]) //Check if character is already found. 
     { 
      flag[str[i]] = 1; //If a character is found for the first time, enable corresponding flag. 
      i++; //Go to next byte in the array. 
     } 
     else 
     { 
      for(j=i; str[j] != '\0'; j++) 
       str[j] = str[j+1]; //If repeated character, shift the array entries to 1 byte left. 
     } 
    } 
} 
+1

供參考:有人提出了一個簡化代碼的建議。見[這裏](http://stackoverflow.com/review/suggested-edits/14481531)。 –

+0

@Aniket Khaire:我不知道我爲什麼不能批准你的編輯。請將它作爲單獨的答案發布。這比我的解決方案好。 – MayurK

+1

由於代碼的重大更改,三位審閱者拒絕了該審閱。 –

0

編輯上面的代碼由MayurK:

char* remove_repeatation(char *str) 
{ 
    char flag[256] = {0}; //Assuming sizeof char is 8. So max 256 different characters. 
    int i   = 0; 
    int j   = 0; 

    for(i=0; str[i] != '\0'; i++) 
    { 
     if(0 == flag[str[i]]) //Check if character is already found. 
     { 
      flag[str[i]] = 1; //If a character is found for the first time, enable corresponding flag. 
      str[j] = str[i]; 
      j++; 
     } 
    } 
    str[j] = '\0'; 
    return *str; 
}