← Back to C Course | Chapter 6: Arrays & Strings | Lesson 7 of 8

C String Functions

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)

c
#include <stdio.h>
#include <string.h>
int main() {
	char str[] = "Hello";
	printf("%zu", strlen(str));
	return 0;
}

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)

c
#include <stdio.h>
#include <string.h>
int main() {
	char dest[20];
	strcpy(dest, "Hello");
	printf("%s", dest);
	return 0;
}

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)

c
#include <stdio.h>
#include <string.h>
int main() {
	char str[20] = "Hello ";
	strcat(str, "World");
	printf("%s", str);
	return 0;
}

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)

c
#include <stdio.h>
#include <string.h>
int main() {
	printf("%d", strcmp("apple", "banana"));
	return 0;
}

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)

c
#include <stdio.h>
#include <string.h>
int main() {
	char *result = strstr("concatenate", "cat");
	printf("%s", result);
	return 0;
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.