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

Strings in C: solved exercise

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

Problem statement

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

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#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;
}

Expected output

1
2
3
cmp=0
copy=hello
len=5

Test strings near buffer limits to validate null termination:

1
a = "1234567890123456789012345678901"   // 31 chars

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

Common mistakes

  • 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.

Time and space complexity

  • strlen, strcpy, strcmp: O(n) with respect to string length.
  • Extra space: O(1) (excluding input/output buffers).

Practical use

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

Guided practice and next step

If you want a complete path with progressive difficulty:

FAQ

Is this exercise useful for C exams and technical interviews?

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

Where can I keep practicing with more solved C exercises?

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

How should I practice this exercise type to improve faster?

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