Lesson 13 of 23
uniq
The uniq Command
uniq removes consecutive duplicate lines. Only adjacent duplicates are removed — non-adjacent duplicates are kept:
$ printf "apple\napple\nbanana\nbanana\napple\n" | uniq
apple
banana
apple
The first two apple lines collapse into one. The final apple stays because it is not adjacent to another apple.
Your Implementation
Write void my_uniq(const char *s) that prints deduplicated lines.
You need to remember the previous line and compare it to the current one. If they are different, print the current line. If they are the same, skip it.
void my_uniq(const char *s) {
char prev[256];
char line[256];
prev[0] = '\0';
while (*s) {
char *out = line;
while (*s && *s != '\n') { *out++ = *s++; }
*out = '\0';
if (*s == '\n') s++;
// Compare line with prev using pointer arithmetic
const char *a = line, *b = prev;
while (*a && *a == *b) { a++; b++; }
if (*a != *b) {
printf("%s\n", line);
// Copy line into prev
char *d = prev;
const char *c = line;
while (*c) *d++ = *c++;
*d = '\0';
}
}
}
Pointer-based String Compare and Copy
Instead of strcmp and strcpy from <string.h>, we compare and copy with pointer loops:
- Compare: walk both pointers together until a mismatch or end. If the final characters differ, the strings differ.
- Copy: walk
srcand write each character todestuntil the null terminator.
This is exactly what strcmp and strcpy do internally — writing them yourself is great practice.
Your Task
Implement my_uniq that removes consecutive duplicate lines.
TCC compiler loading...
Loading...
Click "Run" to execute your code.