Strings in C: solved exercises with strlen, strcpy, and strcmp

  2 minutes

If you searched for strings in C solved exercises, this example covers core string.h operations.

Compare two strings, copy one of them, and print its length.

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

int main(void) {
    char a[32] = "hello";
    char b[32] = "hello";
    char copy[32];

    int cmp = strcmp(a, b);
    strcpy(copy, a);

    printf("cmp=%d\n", cmp);
    printf("copy=%s\n", copy);
    printf("len=%zu\n", strlen(copy));
    return 0;
}
cmp=0
copy=hello
len=5

Test strings near buffer limits to validate null termination:

a = "1234567890123456789012345678901"   // 31 chars

If you forget room for \0, you get overflow risk.

  • Not allocating room for \0.
  • Using strcpy without size checks.
  • Comparing strings with == instead of strcmp.
  • Forgetting to trim trailing \n from fgets input before comparisons.
  • strlen, strcpy, strcmp: O(n) with respect to string length.
  • Extra space: O(1) (excluding input/output buffers).

String handling is essential for parsing logs, commands, and text-based inputs.

If you want a complete path with progressive difficulty:

Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.

In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.