在C语言中,如何删除char数组中相同且连续的行? [英] In C, how do I remove identical, and consecutive lines in a char array?

查看:75
本文介绍了在C语言中,如何删除char数组中相同且连续的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在创建函数时正在寻求帮助。

I'm looking for some help in creating a function.

函数funcion deleteIdents()将删除char数组中相同的行,因为它们是连续的。

The funciton, deleteIdents(), will remove identical lines in a char array, given they are consecutive. It will keep one of the identical lines.

我不需要检查整个行是否相同。在这种情况下,仅前79个字符MAXCHARS就可以了。

I don't need to check if the whole line is identical. Just the first 79 chars, MAXCHARS, will be fine for this scenario.

因此,例如,如果我的数组包含

So, for example, if my array contains

Hello World
Hi World
Hello World
Hello World
Hello World
Hi there

它将更改为

Hello World
Hi World
Hello World
Hi there

在我看来,该函数类似于:

In my head, the function would look similar to:

int deleteIdents(char *a)
{
    int i;
    for (i=0; i<=MAXCHARS; i++) {
        if (a[i] != '\n')
            /* copy into new array */
        }
    }
}

但我不确定。如果您有解决方案,我会很高兴和感激:)

but I'm unsure. If you have a solution, I'd be glad and thankful to hear it :)

推荐答案

如何实现此目标的另一个示例。想法是保留2个指针,并且仅当条目不同时才递增第一个指针。

Another example how it can be achived. Idea is to keep 2 pointers, and increment first one only if entries are different. Also some additional storage is allocated to avoid memory leaks for entries that has been overriden.

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

int unique(char **strings, int size) {
    if (!strings) {
        return -1;
    }
    int head = 0, newHead = 0, duplicatedElementsHead = 0;
    //Save duplicates to avoid memory leaks
    char** duplicatedEntries = malloc(size*sizeof(char*));

    while (head < size) {
        //String are the same
        if (!strcmp(strings[head], strings[newHead])) {
            if (head != newHead) {
                duplicatedEntries[duplicatedElementsHead++] = strings[newHead];
            }
            ++head;
        } else {
            strings[++newHead] = strings[head++];
        }
    }

    //Put duplicated entries after new end
    int idx = 0, tmpHead = newHead + 1;
    for (; idx < duplicatedElementsHead; ++idx) {
        strings[tmpHead++] = duplicatedEntries[idx];
    }

    free(duplicatedEntries);
    return newHead;
}

int main() {
    char **strings = malloc(8*sizeof(char*));
    strings[0] = "Hello World";
    strings[1] = "Hi World";
    strings[2] = "Hi World";
    strings[3] = "Hello World";
    strings[4] = "Hello World";
    strings[5] = "Hi there";
    strings[6] = "Hia";
    strings[7] = "Hi";
    int newEnd = unique(strings, 8);
    for (int i=0; i < newEnd; ++i) {
        printf("%s\n", strings[i]);
    }
    free(strings);
}

这篇关于在C语言中,如何删除char数组中相同且连续的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆