Remove identical, consecutive lines in a char arra

2020-05-09 22:23发布

I'm trying to create a function that will detect if there are consecutive lines in a char array that are identical.

For example, if a char array contained:

Hi

Hello

Hello

Hello

Hello

then the array would be changed to

Hi

Hello

Essentially, I want to detect the consecutive, identical lines, and delete them so only one of the lines remains. If one line is identical to a earlier line, but they are not consecutive, then it's fine.

Really, the whole line doesn't have to be identical, but at least the first 79, or MAXCHARS, have to be identical.

Additionally, I don't want to do this by writing to an intermediate file. Ideally, I would store data in arrays instead.

I was thinking something like:

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

but I'm somewhat lost. I don't want to print the array right now, because I will be altering it again later in my program; I still need to use a.

Any help/solution is greatly appreciated. Thank you.

1条回答
smile是对你的礼貌
2楼-- · 2020-05-09 23:07

Some guidance:

  • You only ever to copy each character at most once - backwards, to its destination. No need for extra copies.
  • You'll have a "finalized up to here" position in the array and a "being processed/read" position.
  • Keep track of the current full-line which may be duplicated, and match each new line against it to check whether it's a dupe.
  • Advance by full lines rather than by characters - except when looking for the next end-of-line.
查看更多
登录 后发表回答