Skip to main content

union — String Union

Allowed functions: write

Write a program that takes two strings and displays, without doubles, the characters that appear in either one of the strings.

The display will be in the order characters appear in the command line, and will be followed by a newline. If the number of arguments is not 2, the program displays a newline.

Examples

$>./union zpadinton "paqefwtdjetyiytjneytjoeyjnejeyj" | cat -e
zpadintoqefwjy$
$>./union ddf6vewg64f gtwthgdwthdwfteewhrtag6h4ffdhsd | cat -e
df6vewg4thras$
$>./union "rien" "cette phrase ne cache rien" | cat -e
rienct phas$
$>./union | cat -e
$

Solution

Download union.c
#include <unistd.h>

int main(int c, char **v) {
if (c != 3) {
write(1, "\n", 1);
return 0;
}
int seen[256] = {0};
int i, j;
j = 1;
while (j <= 2) {
i = 0;
while (v[j][i]) {

if (!seen[(int)(unsigned char)v[j][i]]) {
seen[(int)(unsigned char)v[j][i]] = 1;
write(1, &v[j][i], 1);
}
i++;
}

j++;
}
write(1, "\n", 1);
return 0;
}

How It Works

Goal: Display all unique characters from both strings combined, in the order they first appear.

Approach: Iterate through the first string then the second, printing each character only the first time it is encountered using a lookup table.

Step by step:

  1. If the argument count is not 3, print a newline and exit.
  2. Initialize a seen[256] array to zero (one entry per possible unsigned char value).
  3. Loop through v[1] then v[2] (using j from 1 to 2).
  4. For each character, if seen is 0, print it and set seen to 1.
  5. Print a trailing newline.

Key concept: A 256-entry boolean lookup table that maps every possible character value to a "printed" flag, guaranteeing each character is output exactly once.