What are Remove Common Characters in C- C Programming Tutorials For Beginners

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Strings

Remove Common Characters in C

Nested loops versus a lookup table, plus a complete strings quiz and interview questions.

Here is a classic string puzzle: given two strings, delete every character that appears in both and show what is left of each. Learning to remove common characters from two strings in C trains you to think about character sets, nested loops, and then a smarter solution that uses a small lookup table. It also closes the strings chapter of our free C programming course, so at the end of this lecture you will find a quiz and a set of interview questions covering everything from sscanf to word counting. The techniques apply directly to embedded C programming, for example when sanitising input from a serial port.

What You Will Learn

  • How to define “common characters” precisely so the problem has one correct answer
  • How to remove common characters from two strings in C with nested loops
  • How to rewrite it as a lookup table that needs only one pass per string
  • Why you need separate output buffers and must not edit an input while comparing
  • How to read both strings safely with fgets
  • A complete quiz, output-prediction drills and interview questions on C strings

Prerequisites

You need char arrays, string loops, functions that take pointers, and the idea that a char is a small integer that can index an array. The earlier lectures in this free C tutorial on sscanf, input validation and character handling are enough.

Remove Common Characters From Two Strings in C: The Problem

Take firmware and hardware. The letters r, w, a and e occur in both words. Remove those letters from each word and you are left with fim and hd. Notice what the rule really says: a character is deleted from one string if it appears anywhere in the other string. It does not matter how many times it appears, and the letters m and d that stay behind are only removed from the string where they are unique.

What counts as common: letters present in both strings
first string: firmware
firmwae
second string: hardware
hardwe
highlighted letters are common, they are removed from BOTH strings
first becomes: fimsecond becomes: hd

Two details prevent bugs later. First, both results must be computed from the original strings, so you cannot shorten the first string and then compare the second against the shortened copy. Second, the answers go into separate output arrays, which also keeps your input strings intact and usable afterwards.

Remove Common Characters From Two Strings in C With Nested Loops

The direct approach asks, for every character of one string, whether it occurs in the other. A small helper function named contains answers that question by scanning. The main function calls it once per character, for each string in turn.

#include <stdio.h>

static int contains(const char *s, char c)
{
    for (; *s != '\0'; s++)
        if (*s == c)
            return 1;
    return 0;
}

static void remove_common(const char *a, const char *b, char *out_a, char *out_b)
{
    size_t k = 0;

    for (size_t i = 0; a[i] != '\0'; i++)
        if (!contains(b, a[i]))
            out_a[k++] = a[i];
    out_a[k] = '\0';

    k = 0;
    for (size_t i = 0; b[i] != '\0'; i++)
        if (!contains(a, b[i]))
            out_b[k++] = b[i];
    out_b[k] = '\0';
}

int main(void)
{
    const char *pairs[][2] = {
        { "firmware", "hardware" },
        { "kernel",   "driver"   },
        { "abc",      "xyz"      },
        { "same",     "same"     }
    };
    const int count = (int)(sizeof pairs / sizeof pairs[0]);

    for (int i = 0; i < count; i++) {
        char ra[64], rb[64];
        remove_common(pairs[i][0], pairs[i][1], ra, rb);
        printf("%-9s + %-9s -> [%s] and [%s]\n", pairs[i][0], pairs[i][1], ra, rb);
    }
    return 0;
}

Compile and run:

gcc -std=c17 -Wall -Wextra -o remove_common remove_common.c
./remove_common
firmware  + hardware  -> [fim] and [hd]
kernel    + driver    -> [knl] and [div]
abc       + xyz       -> [abc] and [xyz]
same      + same      -> [] and []

The output lines show the edge cases that a good test must include. abc and xyz have nothing in common, so both strings survive unchanged. Two identical strings lose every character, leaving empty strings. Notice how the program writes a terminating null byte after the last kept character, which is what turns the output array into a valid C string.

The output buffers must be large enough for the worst case, which is the full length of the input plus one byte for the terminator. In this demo they have 64 bytes and the test words are short. In your own code compute the size from the input, or pass the buffer size into the function and stop writing when it is full.

The cost of this version is n times m comparisons in the worst case, where n and m are the string lengths. For short command words it is perfectly fine. For long text it grows fast.

Remove Common Characters From Two Strings in C With a Lookup Table

Since a char is just a small number, you can use it as an array index. Keep one table of 256 flags for each string, one slot per possible byte value. First walk a string and set the flag of every character you meet. After that, asking “does this character occur in the string?” is a single array read instead of a scan.

Lookup table method: remember letters once, then filter
step 1: mark every character of the first string in a 256-slot table
f=1i=1r=1m=1w=1a=1e=1all other slots = 0
step 2: walk the second string, keep a character only if its slot is 0
h keepa dropr dropd keepw drope drop
result: hd (the same two steps, swapped, give fim for the first string)

The program below reads the two strings with fgets and applies the two steps. The helper functions mark and filter are tiny, and each string is traversed a fixed number of times.

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

static void mark(const char *s, unsigned char seen[256])
{
    for (; *s != '\0'; s++)
        seen[(unsigned char)*s] = 1;
}

static void filter(const char *s, const unsigned char other[256], char *out)
{
    size_t k = 0;

    for (; *s != '\0'; s++)
        if (!other[(unsigned char)*s])
            out[k++] = *s;
    out[k] = '\0';
}

int main(void)
{
    char first[80], second[80];
    char left[80],  right[80];
    unsigned char in_first[256]  = { 0 };
    unsigned char in_second[256] = { 0 };

    printf("First string : ");
    if (fgets(first, sizeof first, stdin) == NULL) return 1;
    printf("Second string: ");
    if (fgets(second, sizeof second, stdin) == NULL) return 1;

    first[strcspn(first, "\n")]   = '\0';
    second[strcspn(second, "\n")] = '\0';

    mark(first, in_first);
    mark(second, in_second);
    filter(first, in_second, left);
    filter(second, in_first, right);

    printf("\nfirst  after removal: [%s]\n", left);
    printf("second after removal: [%s]\n", right);
    return 0;
}

Run it with piped input:

printf 'firmware\nhardware\n' | ./remove_common_fast
First string : Second string: 
first  after removal: [fim]
second after removal: [hd]

The prompts run together because the piped input produces no visible keystrokes; at a keyboard they appear on separate lines. The result is the same as the nested-loop version: fim and hd.

Why the unsigned char cast matters: a plain char may be signed, so a byte above 127 would give a negative index and read outside the table. Casting to unsigned char first guarantees an index from 0 to 255.

Why the table wins as strings grow
nested loops: every character of one string is compared with every character of the other
n charactersxm charactersn * m comparisons
lookup table: one pass to mark, one pass to filter
n+mn + m steps
PropertyNested loopsLookup table
TimeProportional to n times mProportional to n plus m
Extra memoryNone beyond output buffersTwo tables of 256 bytes
Code lengthShortest and easiest to readA little longer
Best forShort strings, tiny RAMLonger text, repeated use

Both versions were checked against each other on 200,000 randomly generated string pairs, and the results were identical every time. On a very small microcontroller you can shrink each table to a 32-byte bitmap, one bit per possible character, at the price of a few shift and mask operations.

Where This Is Useful in Embedded Systems

  • Input filtering. Removing or rejecting characters from a set of forbidden or allowed symbols before a command is processed.
  • Protocol cleanup. Stripping separators such as colons or dashes from a MAC address or serial number before conversion.
  • Set operations on text. Finding which letters two identifiers share, for test tools and log checkers.
  • Presence tables in general. The 256-slot flag array is a pattern you will reuse for counting, histogramming and validating bytes.

Common Mistakes When You Remove Common Characters

MistakeResultFix
Editing the first string, then filtering the second against itWrong answer for the second stringAlways compare with the originals
Forgetting the terminating null in the outputGarbage after the resultWrite the null byte after the last kept character
Output buffer too smallBuffer overflowSize it as input length plus one
Using scanf with %sStops at spaces and may overflowUse fgets and strip the newline
Indexing the table with a plain charNegative index for high bytesCast to unsigned char
Not clearing the tableLeftover flags from a previous runInitialise to zero every time

Best Practices, Performance and Security

  • Write the filter as a function with explicit input and output arguments so it can be tested on its own.
  • Choose the lookup table when strings may be long or the function runs often, and nested loops when RAM is the tighter limit.
  • Treat the size of every output array as part of the function contract.
  • Remember that these methods compare bytes, not letters. Upper and lower case are different characters unless you convert them first.
  • Remove characters only after validating where the data came from. Silently deleting bytes from untrusted input can change its meaning.

Summary and Key Takeaways

  • To remove common characters from two strings in C, delete from each string every character found in the other.
  • Compute both results from the original strings into separate output arrays.
  • Nested loops are simple but cost n times m comparisons.
  • A 256-slot lookup table needs one marking pass and one filtering pass, so n plus m steps.
  • Cast to unsigned char before using a character as an index, and terminate every output string.

C Strings Quiz: Test Yourself

Answer each question on paper first, then open the answers at the end of the section.

  1. What does sscanf return when the input string is empty and the first conversion is %d?

    • A) 0
    • B) 1
    • C) EOF
    • D) It is undefined
  2. Which format item stores the number of characters consumed so far and is not counted in the return value?

    • A) %c
    • B) %n
    • C) %p
    • D) %i
  3. The variable v holds 7. After sscanf(“abc”, “%d”, &v) what are the return value and v?

    • A) 1 and 0
    • B) 0 and 0
    • C) 0 and 7
    • D) EOF and 7
  4. Why must you cast a char to unsigned char before calling isalpha?

    • A) To make it run faster
    • B) Negative values cause undefined behaviour
    • C) isalpha only accepts unsigned types by syntax
    • D) It converts the character to upper case
  5. Which function replaced the removed gets for reading a line?

    • A) puts
    • B) getchar
    • C) fgets
    • D) scanf with %s
  6. After sscanf(“42abc”, “%d%n”, &v, &used) what is used?

    • A) 0
    • B) 2
    • C) 3
    • D) 5
  7. With char c = ‘7’; what does printf(“%d”, c – 32) print?

    • A) 87
    • B) 23
    • C) 55
    • D) 7
  8. Which string is a palindrome when characters are compared exactly as stored?

    • A) Level
    • B) level
    • C) Noon
    • D) Radar
  9. Spaces plus one applied to “a b” (two spaces between the letters) gives which count?

    • A) 1
    • B) 2
    • C) 3
    • D) 4
  10. What is the time cost of the lookup-table method for strings of lengths n and m?

    • A) Proportional to n plus m
    • B) Proportional to n times m
    • C) Proportional to n squared
    • D) Constant
Show quiz answers
  1. C. EOF is returned when input ends before the first conversion.

  2. B. %n records the consumed character count and is not counted as a conversion.

  3. C. Nothing matched, so it returns 0 and v keeps 7.

  4. B. The ctype functions require EOF or an unsigned char value.

  5. C. fgets takes the buffer size and cannot overflow it.

  6. B. Two digits were consumed before the letter a.

  7. B. The digit 7 has code 55, and 55 minus 32 is 23.

  8. B. level matches exactly. Level, Noon and Radar start with a capital, which differs from the lower-case letter at the end.

  9. C. There are two spaces, and spaces plus one gives 3, but the real number of words is 2.

  10. A. One pass to mark and one to filter.

Predict the Output

Work out what each snippet prints, then check the answers underneath.

Snippet 1

int a = 0, b = 0;
int r = sscanf("10 20", "%d,%d", &a, &b);
printf("%d %d %d\n", r, a, b);

Snippet 2

int v = 7;
int r = sscanf("3.75", "%d", &v);
printf("%d %d\n", r, v);

Snippet 3

char s[] = "abcd";
size_t n = strlen(s);
for (size_t i = 0, j = n - 1; i < j; i++, j--) {
    char t = s[i]; s[i] = s[j]; s[j] = t;
}
printf("%s\n", s);

Snippet 4

char name[8] = "";
int  id = 0;
int  r = sscanf("node 12", "%7s %d", name, &id);
printf("%d %s %d\n", r, name, id);
Show answers
  1. Prints 1 10 0. The comma in the format does not match the space in the input, so only a is stored.

  2. Prints 1 3. %d reads the 3 and stops at the dot.

  3. Prints dcba. The loop swaps the outer pair and then the inner pair.

  4. Prints 2 node 12. Both fields converted.

Programming Challenges

  1. Write a function that parses a line of the form key=value into a key string and an integer, rejecting any extra text.
  2. Extend the palindrome checker so that it returns the index of the first mismatch, or -1 when the text is a palindrome.
  3. Count the vowels and consonants in a line read with fgets.
  4. Write a case-insensitive command matcher that accepts set, Set and SET but not sets.
  5. Remove all duplicate characters from one string, keeping the first occurrence of each, using a lookup table.

C Strings Interview Questions

1. What is the difference between scanf, sscanf and fscanf?

They share the same format language and differ only in the source. scanf reads from standard input, fscanf from a FILE stream, and sscanf from a string in memory.

2. Why should you always check the return value of sscanf?

It tells you how many conversions succeeded. If a field fails, later variables keep their old values, so unchecked results can be stale or garbage.

3. How do you stop %s from overflowing an array?

Give it a width that is one less than the array size, for example %7s for char buf[8], so room remains for the null terminator.

4. Why is strtol preferred to atoi?

strtol reports where conversion stopped through endptr and signals out-of-range values with errno set to ERANGE. atoi returns 0 for garbage and gives no error information.

5. Why is modifying a string literal undefined behaviour?

Literals may be placed in read-only memory, and the standard does not allow modifying them. Copy the text into a char array if you need to change it.

6. Why was gets removed from C?

It has no way to limit the number of characters it writes, so it can always overflow the destination. It was removed in C11, and fgets is the safe replacement.

7. How do you reverse a string in place, and what is the pitfall?

Swap characters from both ends while the left index is less than the right. The pitfall is strlen(s) – 1 on an empty string, which wraps because size_t is unsigned, so check the length first.

8. Why does counting spaces plus one fail to count words?

It breaks on repeated, leading and trailing spaces, tabs and empty lines. Count transitions from white space to a non-space character instead.

9. What is an efficient way to find common characters in two strings?

Mark every character of one string in a 256-entry table and test each character of the other against it. That is O(n + m) time with a fixed amount of extra memory.

10. Why cast to unsigned char for ctype functions and table indexes?

The ctype functions require EOF or an unsigned char value, and a plain char can be negative. The same cast prevents negative array indexes.

11. What does clearing bit 5 do to an ASCII letter?

It converts a lower-case letter into its capital, because the two differ only in that bit. It must be applied only after confirming the character is a letter.

Conclusion

To remove common characters from two strings in C you first need a precise definition, then a clean comparison against the original strings, and finally a choice between a simple nested loop and a faster lookup table. The same skills, plus those from the sscanf, validation, palindrome, case conversion and word counting lectures, make up the string toolkit of every embedded programmer. Work through the quiz and the challenges, revisit any lecture where an answer surprised you, and move on to the next chapter of our free C programming course and the wider free embedded C course.

Frequently Asked Questions About Removing Common Characters in C

How do I remove common characters from two strings in C?

Mark the characters of each string, then copy only those characters of the other string whose mark is not set. Nested loops with a contains helper do the same job more slowly.

What is the fastest method?

A lookup table with 256 flags, one per possible byte value. It takes one pass to mark and one to filter, so the time is proportional to the sum of the lengths.

Why do I need two output arrays?

Each result must be computed from the original strings. Writing into one of the inputs would change what the other is compared against.

Does it matter how many times a character occurs?

No. A character is removed from a string if it appears at least once in the other string.

Why cast the character to unsigned char when indexing the table?

A plain char may be negative for bytes above 127, which would index before the start of the array.

Is this case sensitive?

Yes. The comparison is by byte value, so A and a are different. Convert both strings to one case first if you want to ignore it.

Where can I practise more C string questions?

Work through the quiz and challenges in this lecture, then redo the earlier programs in the strings chapter without looking at the solutions.

Finish Strong With the Free C Tutorial

You have completed another chapter step. Continue with the next chapter of the free embedded C course.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →