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
#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
cmp=0
copy=hello
len=5Recommended edge case
Test strings near buffer limits to validate null termination:
a = "1234567890123456789012345678901" // 31 charsIf you forget room for \0, you get overflow risk.
Common mistakes
- Not allocating room for
\0. - Using
strcpywithout size checks. - Comparing strings with
==instead ofstrcmp. - Forgetting to trim trailing
\nfromfgetsinput 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.
Recommended next exercise
- Matrices in C: solved main and secondary diagonal exercise
- Files in C: solved exercise to count lines and characters
- Bubble sort in C: solved exercise step by step
- All C exercises
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.