在文本文件中,我有“abbcccdddd”。我想将“abcd”存储在一个数组中。
之前: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++;
}
}
答案 0 :(得分: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 :(得分: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;
}