Beginner · Strings in C · topic 17 of 60 · 30 min
The <string.h> functions
Explanation
Length and comparison
#include <string.h>
size_t n = strlen("Mumbai"); /* 6 */
int r = strcmp("apple", "banana"); /* negative: "apple" comes first */
int s = strcmp("chai", "chai"); /* 0: equal */
int t = strcmp("Zebra", "apple"); /* negative: 'Z' (90) < 'a' (97) in ASCII */
if (strcmp(input, "yes") == 0) { … } /* the correct way to test equality */Copying and appending
char dest[20];
strcpy(dest, "Hello"); /* copies including '\0'; NO size check */
strcat(dest, ", Pune"); /* appends; NO size check */
/* if the result does not fit in 20 bytes: buffer overflow (undefined behaviour) */
char safe[10];
snprintf(safe, sizeof safe, "%s, %s", "Hello", "Pune"); /* writes at most 9 chars + '\0' */
/* safe = "Hello, Pu" (truncated, but no overflow) */The strncpy trap
char code[4];
strncpy(code, "PUNE", sizeof code); /* copies 'P','U','N','E': NO room left, so NO '\0' added! */
code[sizeof code - 1] = '\0'; /* you must terminate it yourself → "PUN" */strncat(dest, src, n) appends at most n characters AND always adds \0, but n is the space REMAINING, not the total size: strncat(dest, src, sizeof dest - strlen(dest) - 1).
Searching
const char *email = "asha@bank.in";
char *at = strchr(email, '@'); /* pointer to the '@', or NULL if absent */
if (at) printf("Domain: %s\n", at + 1); /* Domain: bank.in */
char *p = strstr("order-2026-OD55", "OD"); /* pointer to the first "OD" or NULL */Raw memory: memcpy, memset, memcmp
int a[5] = {1, 2, 3, 4, 5}, b[5];
memcpy(b, a, sizeof a); /* copy 20 bytes (non-overlapping regions only; use memmove if they overlap) */
memset(b, 0, sizeof b); /* set every byte to 0 */
int same = memcmp(a, b, sizeof a) == 0;Writing your own strlen
size_t my_strlen(const char *s) {
size_t n = 0;
while (s[n] != '\0') n++; /* walk until the terminator */
return n;
}Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
The <string.h> functions · 1/6
In this lesson you will use the string functions from string dot h.
Prefer a video by a teacher? Find free videos on “c string.h functions strcpy strcmp strcat snprintf tutorial” on YouTube ↗
In real life: Building an SMS from parts
A bank's alert service builds SMS text from the account's last four digits, the amount and the date, into a fixed 160-byte buffer. snprintf guarantees the message can never overflow the buffer, whatever the data.
char sms[161];
const char *last4 = "4321";
double amount = 1250.0;
snprintf(sms, sizeof sms, "Rs %.2f debited from A/c XX%s on %s. Not you? Call 1800-XXX-XXXX",
amount, last4, "19-10-26");
printf("%s (%zu chars)\n", sms, strlen(sms));Practice (0/3 done)
What does this print? char a[] = "Chai", b[] = "chai"; printf("%d\n", strcmp(a, b) == 0);
char buf[8]; strcpy(buf, "Bengaluru"); What happens?
Write size_t my_strlen(const char *s), int my_strcmp(const char *a, const char *b) (returning <0, 0 or >0 like strcmp) and a function that builds "Name: <name>, City: <city>" into a caller-supplied buffer with snprintf, returning 0 on success and -1 if the text was truncated (snprintf returns the length it WANTED to write).
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Reading strings safelyStrings in C · same module
- Characters and <ctype.h>Strings in C · same module
- Dynamic strings and 2D arraysDynamic memory
- Strings, bytes and runesGo Programming (backend and cloud) · Collections and structs
- Strings in depthJava Programming (Core to Spring Boot) · Arrays and strings
- Strings: methods, interpolation, verbatim and raw stringsC# and .NET · Arrays, strings and null
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
strcmp("abc", "abd") returns…
Answer: A negative number
'c' < 'd'.
Which function always respects the buffer size and terminates the result?
Answer: snprintf
snprintf writes at most size - 1 chars plus \0.
strchr("asha@bank.in", '@') returns…
Answer: A pointer to the @ character
It returns a pointer, or NULL if not found.
When source and destination memory overlap, use…
Answer: memmove
memcpy with overlapping regions is undefined behaviour.
What does atoi("abc") return?Related
Answer: 0, indistinguishable from the input "0"
That is why strtol is preferred.
int a[] = {4, 5, 6, 7}; What is sizeof a / sizeof a[0]?Related
What does snprintf(NULL, 0, "%d", 12345) return?Related
Answer: 5
The number of characters the text would need (without the terminator).
How many bytes does "UPI" occupy as a string literal?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 3 more topics in “Strings in C” before its exam: Reading strings safely, Characters and <ctype.h>, Buffer overflows and safe string handling.
- Module 4 exam: Strings in C · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Pointers. 60 topics left in the course before the final exam.