Remove identical, consecutive lines in a char array in C

拥有回忆 提交于 2019-12-04 07:02:12

问题


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:


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.


来源:https://stackoverflow.com/questions/50032662/remove-identical-consecutive-lines-in-a-char-array-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!