String Functions
Challenge Gallery
Quick Reference
String functions (#include <string.h>):
| Function | Purpose | Gotcha |
|---|---|---|
strlen(s) |
Length (not counting '\0') |
Returns size_t, not int |
strcmp(a, b) |
Compare: <0, 0, >0 | Never use == on strings |
strcpy(dest, src) |
Copy src into dest | No bounds checking |
strncpy(dest, src, n) |
Bounded copy | May not null-terminate |
strcat(dest, src) |
Append src to dest | No bounds checking |
strcspn(s, reject) |
Index of first char in reject | Used for newline stripping |
Character functions (#include <ctype.h>):
| Function | Tests/Converts |
|---|---|
isalpha(c) |
Is it a letter? |
isdigit(c) |
Is it a digit? |
isupper(c) / islower(c) |
Case check |
toupper(c) / tolower(c) |
Case conversion |
Safe input pattern:
char buf[100];
fgets(buf, sizeof(buf), stdin); // Safe read
buf[strcspn(buf, "\n")] = '\0'; // Strip newline
Java → C string comparison:
| Java | C |
|---|---|
s.equals("hello") |
strcmp(s, "hello") == 0 |
s.length() |
strlen(s) |
s.charAt(i) |
s[i] |
s1 + s2 |
strcpy then strcat |
Common Pitfalls
==compares addresses, not content — Always usestrcmp. Two identical strings at different addresses →==says false.- Buffer overflow with strcpy/strcat/scanf — No bounds checking. Use bounded variants or
fgets. - Off-by-one: forgetting
'\0'— A 5-character string needs a 6-byte buffer. Always allocatestrlen + 1. - fgets includes the newline — Strip it with
buf[strcspn(buf, "\n")] = '\0';. - Never use gets() — Removed from C11. CWE-242. Use
fgets().