2016-11-30 61 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; 
}