2016-11-30 14 views
0

テキストファイルには "abbcccdddd"があります。私は "abcd"を配列に格納したい。前C文字配列内の重複する文字を削除します。

:TX [0]、TX [1] = B、TX [3] = Cを、TX [6] =後D

=:TX [0] 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

FYI:誰かがあなたのコードを簡素化するための提案をしました。 [ここ](http://stackoverflow.com/review/suggested-edits/14481531)を参照してください。 –

+0

@Aniket Khaire:あなたの編集を承認できない理由はわかりません。別の回答として投稿してください。それは私の解決策よりも優れています。 – MayurK

+1

コードの大幅な変更のために3人の査読者が拒否したときにレビューが完了しました。 –

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; 
} 
関連する問題