C String Functions
In this page:
Finding String Length (strlen)
strlen() has to scan the string character by character until it finds the null terminator, making it an O(n) operation -- calling it repeatedly inside a loop condition (like for (i=0; i<strlen(s); i++)) silently re-scans the whole string on every iteration.
Example: Finding String Length (strlen)
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello";
printf("%zu", strlen(str));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Copying Strings (strcpy)
strcpy() performs no bounds checking on the destination buffer, so if the source string is longer than the destination array, it overflows into adjacent memory -- strncpy() with an explicit length limit is the safer alternative in most modern code.
Example: Copying Strings (strcpy)
#include <stdio.h>
#include <string.h>
int main() {
char dest[20];
strcpy(dest, "Hello");
printf("%s", dest);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Concatenating Strings (strcat)
strcat() has the same overflow risk as strcpy() since it doesn't check whether the destination buffer has enough remaining space for the appended text -- always make sure the destination was allocated large enough to hold both strings combined.
Example: Concatenating Strings (strcat)
#include <stdio.h>
#include <string.h>
int main() {
char str[20] = "Hello ";
strcat(str, "World");
printf("%s", str);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Comparing Strings (strcmp)
This return convention mirrors how strcmp mimics alphabetical ordering internally by comparing character codes one pair at a time, so apple compares less than banana because a has a smaller character code than b.
Example: Comparing Strings (strcmp)
#include <stdio.h>
#include <string.h>
int main() {
printf("%d", strcmp("apple", "banana"));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Searching Strings (strstr)
strstr() is case-sensitive, so searching for "Cat" inside "concatenate" returns NULL even though "cat" appears in it -- this trips people up often enough that case-insensitive searches usually need a custom loop or platform-specific function like strcasestr().
Example: Searching Strings (strstr)
#include <stdio.h>
#include <string.h>
int main() {
char *result = strstr("concatenate", "cat");
printf("%s", result);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: