Strings · Lesson 20 of 35
String Functions in C (string.h)
Because C strings are just arrays, you can't compare them with == or join them with +. The standard header <string.h> provides functions for every common job – length, copy, join, compare, search, split. Knowing them, their pitfalls and how to implement a few yourself is core C knowledge.
In this lesson
- Length, copy and concatenate
- Comparing strings
- Searching and splitting
- Safe alternatives, and writing strlen/strcpy yourself
Length, copy and join
#include <stdio.h>
#include <string.h>
int main(void) {
char first[20] = "Asha";
char last[] = "Verma";
char full[40];
printf("strlen(\"%s\") = %zu, sizeof = %zu\n", first, strlen(first), sizeof first);
strcpy(full, first); // copy: full = "Asha"
strcat(full, " "); // append: "Asha "
strcat(full, last); // "Asha Verma"
printf("full = %s (%zu chars)\n", full, strlen(full));
char safe[8];
snprintf(safe, sizeof safe, "%s %s", first, last); // never writes past the buffer
printf("truncated safely: \"%s\"\n", safe);
return 0;
}
strlen("Asha") = 4, sizeof = 20
full = Asha Verma (10 chars)
truncated safely: "Asha Ve"strcpy and strcat don't check sizes
If the destination is too small, they write past the end – a buffer overflow. Make sure the destination has room for the result plus '\0', or use snprintf, which takes the buffer size and always terminates the string. (strncpy is not a safe strcpy: it doesn't add '\0' when the source is too long.)
Comparing strings
#include <stdio.h>
#include <string.h>
int main(void) {
char a[] = "apple", b[] = "apple", c[] = "banana";
const char *pa = a, *pb = b;
printf("pa == pb ? %s\n", pa == pb ? "same" : "different addresses"); // == compares addresses!
printf("strcmp(a, b) = %d\n", strcmp(a, b));
printf("strcmp(a, c) %s 0\n", strcmp(a, c) < 0 ? "<" : ">");
printf("strcmp(\"Zoo\", \"apple\") %s 0\n", strcmp("Zoo", "apple") < 0 ? "<" : ">"); // 'Z' (90) < 'a' (97)
printf("strncmp(\"interview\", \"internet\", 5) = %d\n", strncmp("interview", "internet", 5));
return 0;
}
pa == pb ? different addresses
strcmp(a, b) = 0
strcmp(a, c) < 0
strcmp("Zoo", "apple") < 0
strncmp("interview", "internet", 5) = 0strcmp returns 0 when the strings are equal, a negative value when the first comes earlier, and a positive value when it comes later – comparing character codes, so upper-case letters sort before lower-case. Never use == to compare strings: it compares addresses.
Searching and splitting
#include <stdio.h>
#include <string.h>
int main(void) {
const char *email = "asha.verma@learnfrenzy.com";
const char *at = strchr(email, '@'); // first '@'
if (at != NULL) {
printf("user = %.*s, domain = %s\n", (int)(at - email), email, at + 1);
}
printf("contains \"frenzy\"? %s\n", strstr(email, "frenzy") ? "yes" : "no");
char csv[] = "Asha,21,Pune,CSE"; // strtok modifies its input: use an array
int field = 1;
for (char *tok = strtok(csv, ","); tok != NULL; tok = strtok(NULL, ",")) {
printf("field %d: %s\n", field++, tok);
}
return 0;
}
user = asha.verma, domain = learnfrenzy.com contains "frenzy"? yes field 1: Asha field 2: 21 field 3: Pune field 4: CSE
| Function | Does |
|---|---|
strlen(s) | number of characters before '\0' |
strcpy(d, s) / strcat(d, s) | copy / append s into d (d must be big enough) |
strcmp(a, b) / strncmp | compare (0 = equal) |
strchr(s, c) / strrchr | pointer to the first / last c, or NULL |
strstr(s, sub) | pointer to the first occurrence of sub, or NULL |
strtok(s, delims) | split into tokens (modifies s; not thread-safe) |
snprintf(buf, size, fmt, …) | safe formatted write into a buffer (in stdio.h) |
Write your own strlen and strcpy
A favourite interview task. Both simply walk the array until '\0':
#include <stdio.h>
size_t my_strlen(const char *s) {
size_t n = 0;
while (s[n] != '\0') n++;
return n;
}
char *my_strcpy(char *dest, const char *src) {
char *start = dest;
while ((*dest++ = *src++) != '\0') { } // copies each char, including the final '\0'
return start;
}
int my_strcmp(const char *a, const char *b) {
while (*a && *a == *b) { a++; b++; }
return (unsigned char)*a - (unsigned char)*b;
}
int main(void) {
char buf[32];
my_strcpy(buf, "LearnFrenzy");
printf("%s has %zu characters\n", buf, my_strlen(buf));
printf("compare: %d %d\n", my_strcmp("cat", "cat"), my_strcmp("cat", "car") > 0);
return 0;
}
LearnFrenzy has 11 characters compare: 0 1
Performance note
strlen walks the whole string every time it's called. Writing for (i = 0; i < strlen(s); i++) makes a loop O(n²). Store the length in a variable first, or loop until s[i] == '\0'.
Practice
Try it yourself
Build the string "ORD-00042" from the number 42 using snprintf.
Show solution
#include <stdio.h> int main(void) { char code[16]; int order = 42; snprintf(code, sizeof code, "ORD-%05d", order); printf("%s\n", code); return 0; }ORD-00042
Quick check
What does strcmp return for equal strings?
0.
strlen vs sizeof for char s[20] = "Hi"?
strlen is 2 (characters); sizeof is 20 (array size in bytes).
Why can't you compare strings with ==?
It compares addresses of the arrays, not their contents.
Summary
- strlen measures, strcpy/strcat copy and join (check sizes!), strcmp compares (0 = equal).
- strchr, strstr and strtok search and split; snprintf builds strings safely.
- All of them just walk characters until '\0' – which is easy to implement yourself.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.