C 删除char数组中的重复字符

标签 c arrays char

在文本文件中,我有“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++;
    }
}

最佳答案

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.
        }
    }
}

关于C 删除char数组中的重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40895410/

相关文章:

php - 如何通过比较删除特定索引

java - 我如何检查Java中一个句子中有多少个辅音和元音?

C++ 字符串函数只返回某些字符

在timeval和clock()之间选择来计算C中的耗时

c - malloced 内存未定义写前读?

c++ - 临时 const 数组未绑定(bind)到右值引用

php - 将 PHP 数组保存到 MySQL?

C++ 在 sprintf_s 中使用带有 sprintf_s 的函数

c - 数组乘法与 sse 内在函数乘法的时间?

c - 堆栈溢出,除非递归下的 printf