C Notes
Master the essential string functions in C including strlen, strcpy, strncpy, strcat, strncat, strcmp, and strncmp with examples, custom implementations, and safety tips.
C provides a powerful set of string manipulation functions through the <string.h> header. These functions handle the most common string operations — measuring length, copying, concatenating, and comparing. Since C strings don't carry size information, understanding how these functions work (and their safety limitations) is critical for writing reliable programs.
Including the String Header
All standard string functions require:
#include <string.h>strlen() - String Length
Returns the number of characters in a string, not counting the null terminator.
Syntax and Usage
size_t strlen(const char *str);#include <stdio.h>
#include <string.h>
int main() {
char greeting[] = "Hello, World!";
size_t len = strlen(greeting);
printf("String: \"%s\"\n", greeting);
printf("Length: %lu\n", len);
printf("sizeof: %lu\n", sizeof(greeting));
return 0;
}String: "Hello, World!" Length: 13 sizeof: 14
Custom Implementation
How strlen Works Internally
strcpy() - String Copy
Copies the source string (including null terminator) into the destination buffer.
Syntax and Usage
char *strcpy(char *dest, const char *src);Source: Programming Destination: Programming
⚠️ The Danger of strcpy
strcpy does NOT check if the destination is large enough. This causes buffer overflow:
Safer Alternative: strncpy
char *strncpy(char *dest, const char *src, size_t n);Safe copy: Hello,
Important:strncpydoes NOT guarantee null termination if the source is longer than n. Always manually add'\0'.
Custom strcpy Implementation
strcat() - String Concatenation
Appends the source string to the end of the destination string.
Syntax and Usage
char *strcat(char *dest, const char *src);Concatenated: Hello, World! Length: 13
How strcat Works
Safer Alternative: strncat
char *strncat(char *dest, const char *src, size_t n);Result: Hello, World
Unlike strncpy, strncat always null-terminates the result.
Custom strcat Implementation
strcmp() - String Comparison
Compares two strings character by character (lexicographically).
Syntax and Return Values
int strcmp(const char *s1, const char *s2);| Return Value | Meaning |
|---|---|
| 0 | Strings are identical |
| < 0 (negative) | s1 comes before s2 lexicographically |
| > 0 (positive) | s1 comes after s2 lexicographically |
#include <stdio.h>
#include <string.h>
int main() {
printf("strcmp(\"apple\", \"apple\") = %d\n", strcmp("apple", "apple"));
printf("strcmp(\"apple\", \"banana\") = %d\n", strcmp("apple", "banana"));
printf("strcmp(\"banana\", \"apple\") = %d\n", strcmp("banana", "apple"));
printf("strcmp(\"Hello\", \"hello\") = %d\n", strcmp("Hello", "hello"));
return 0;
}strcmp("apple", "apple") = 0
strcmp("apple", "banana") = -1
strcmp("banana", "apple") = 1
strcmp("Hello", "hello") = -32Using strcmp for Equality Check
Enter password: secret123 Access granted!
strncmp - Compare First N Characters
int strncmp(const char *s1, const char *s2, size_t n);#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello, World!";
char str2[] = "Hello, C!";
// Compare only first 5 characters
if (strncmp(str1, str2, 5) == 0) {
printf("First 5 characters match!\n");
}
// Compare all characters
if (strcmp(str1, str2) != 0) {
printf("Full strings are different.\n");
}
return 0;
}First 5 characters match! Full strings are different.
Custom strcmp Implementation
Quick Reference Table
| Function | Purpose | Null-safe? | Buffer-safe? |
|---|---|---|---|
strlen(s) | Get length | No | N/A |
strcpy(d, s) | Copy string | No | ❌ No |
strncpy(d, s, n) | Copy up to n chars | No | ⚠️ May not null-terminate |
strcat(d, s) | Append string | No | ❌ No |
strncat(d, s, n) | Append up to n chars | No | ✅ Always null-terminates |
strcmp(s1, s2) | Compare strings | No | N/A |
strncmp(s1, s2, n) | Compare first n chars | No | N/A |
Common Mistakes
Interview Questions
Q1: What's the difference between strcpy and strncpy?
strcpy copies the entire source string regardless of destination size (dangerous). strncpy copies at most n characters, providing buffer overflow protection. However, strncpy may not null-terminate if the source length exceeds n.
Q2: Why does strcmp return an integer instead of a boolean?
The return value indicates the ordering relationship: negative means first string is "smaller" (comes first alphabetically), zero means equal, and positive means first string is "larger". This makes it useful for sorting algorithms.
Q3: What happens if you use == to compare strings in C?
== compares the memory addresses (pointer values), not the string content. Two identical strings at different memory locations will compare as not equal. Always use strcmp() for content comparison.
Q4: Is strlen O(1) or O(n)?
O(n) — strlen must traverse the entire string character by character until it finds '\0'. Unlike some languages where string length is stored separately, C strings have no cached length.
Q5: Can you use strcat on an uninitialized array?
No. strcat looks for the null terminator in the destination to know where to start appending. An uninitialized array has garbage values, so strcat will write to an unpredictable location.
Summary
strlencounts characters until'\0'— returns length excluding the terminatorstrcpycopies strings but is unsafe — preferstrncpywith manual null terminationstrcatappends strings but requires sufficient destination spacestrcmpreturns 0 for equality, negative/positive for ordering- Always use
strcmp()to compare strings — never use== - The
n-variants (strncpy,strncat,strncmp) add length bounds for safety - None of these functions check for NULL pointers — validate inputs first
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for String Functions in C - strlen, strcpy, strcat, strcmp.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this C Programming topic.
Search Terms
c-programming, c programming, programming, strings, string, functions, string functions in c - strlen, strcpy, strcat, strcmp
Related C Programming Topics