String Functions in C (string.h)
You can't copy a string with = or compare two strings with == in C. For these jobs, C gives you ready-made functions in the header file string.h.
In this lesson you will learn the most used string functions: strlen, strcpy, strcat, strcmp, plus a few useful extras. These four are asked in nearly every C exam and viva.
What You Will Learn
- What
string.his. - How to find length with
strlen. - How to copy with
strcpyandstrncpy. - How to join strings with
strcat. - How to compare strings with
strcmpand read its return value. - How to search with
strchrandstrstr.
String Library Functions in C (string.h)
Exam definition: String handling functions are predefined functions declared in the header file <string.h> that perform common operations on strings, such as finding length (strlen), copying (strcpy), joining (strcat) and comparing (strcmp).
Memory trick: Read the names aloud: str + length, str + copy, str + concatenate, str + compare. For copy and cat, the order is like =: destination first, source second (dest = src).
Syntax of Common String Functions
| Function | What it does | Returns |
|---|---|---|
strlen(s) | Counts characters before '\0' | Length (size_t) |
strcpy(dest, src) | Copies src into dest (with '\0') | dest |
strncpy(dest, src, n) | Copies at most n characters | dest |
strcat(dest, src) | Adds src to the end of dest | dest |
strncat(dest, src, n) | Adds at most n characters of src | dest |
strcmp(s1, s2) | Compares character by character | 0 if equal; < 0 or > 0 otherwise |
strchr(s, c) | Finds first character c | Pointer to it, or NULL |
strstr(s, sub) | Finds substring sub | Pointer to it, or NULL |
strrev, strupr and strlwr appear in old Turbo C books, but they are not standard C. GCC doesn't have them. You will write your own in the next lesson.
Example 1: strlen, strcpy and strcat
#include <stdio.h>
#include <string.h>
int main(void)
{
char first[30] = "Virat";
char last[] = "Kohli";
char full[30];
printf("Length of first: %zu\n", strlen(first));
printf("Array size : %zu\n", sizeof(first));
strcpy(full, first); /* full = "Virat" */
strcat(full, " "); /* full = "Virat " */
strcat(full, last); /* full = "Virat Kohli" */
printf("Full name : %s\n", full);
printf("Full length : %zu\n", strlen(full));
return 0;
}
Output
Length of first: 5 Array size : 30 Full name : Virat Kohli Full length : 11
Code Explanation
#include <string.h>brings in the declarations of all string functions.strlen(first)counts letters up to'\0': 5.sizeof(first)is the array size: 30. They are different things.strcpy(full, first)copies "Virat" and its'\0'intofull. Destination comes first.strcat(full, " ")finds the'\0'offull, writes the space there, and puts a new'\0'after it.- The final length is 5 + 1 + 5 = 11.
fullmust be big enough for 12 bytes.
Practice: concatenate two strings in C and find the length of characters in a string.
How strcmp Works
strcmp compares the strings character by character using ASCII values. It stops at the first difference (or when both end).
strcmp("apple", "apply")
a = a, p = p, p = p, l = l, e vs y -> 'e'(101) < 'y'(121) -> negative
strcmp("Zoo", "apple")
'Z'(90) vs 'a'(97) -> 90 < 97 -> negative
(capital letters come BEFORE small letters in ASCII)
| Result of strcmp(s1, s2) | Meaning |
|---|---|
| 0 | s1 and s2 are equal |
| < 0 | s1 comes before s2 (dictionary order) |
| > 0 | s1 comes after s2 |
The exact non-zero number depends on the compiler, so always test with == 0, < 0 or > 0, never with == -1.
Example 2: Password Check and Searching with strcmp, strchr, strstr
#include <stdio.h>
#include <string.h>
int main(void)
{
char saved[] = "india@123";
char typed[] = "india@123";
char email[] = "[email protected]";
char *at, *found;
if (strcmp(saved, typed) == 0)
printf("Password correct\n");
else
printf("Wrong password\n");
if (strcmp("Zoo", "apple") < 0)
printf("\"Zoo\" comes before \"apple\" in ASCII order\n");
at = strchr(email, '@');
if (at != NULL)
printf("Domain: %s\n", at + 1);
found = strstr(email, "fame");
if (found != NULL)
printf("\"fame\" found at index %d\n", (int)(found - email));
return 0;
}
Output
Password correct "Zoo" comes before "apple" in ASCII order Domain: studyfame.com "fame" found at index 13
strcmp(saved, typed) == 0is the correct way to check equal strings.saved == typedcompares addresses, which are never equal for two arrays.strchrreturns a pointer to the'@'.at + 1points to the next character, so printing it shows the domain.found - emailsubtracts two addresses and gives the index where "fame" starts.- Always check for
NULLbefore using the result ofstrchr/strstr.
Safe Versions: strncpy and strncat
strcpy and strcat don't check if the destination is big enough. The n versions limit how much is copied:
char small[6];
strncpy(small, "Bangalore", sizeof(small) - 1); /* copies "Banga" */
small[sizeof(small) - 1] = '\0'; /* strncpy may not add '\0' */
strncpy does not add '\0' if the source is too long, so add it yourself.
Important Points to Remember
- Include <string.h> to use string functions.
- strlen doesn't count
'\0'; sizeof gives the array size. - strcpy/strcat: destination first, and it must be big enough.
- Compare strings with strcmp(...) == 0, never with
==. - strcmp returns 0, negative or positive.
- strrev, strupr, strlwr are not standard C.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
if (s1 == s2) | Compares addresses: always false | if (strcmp(s1, s2) == 0) |
if (strcmp(s1, s2)) to test equality | True when they are different | Write == 0 clearly |
strcpy(src, dest) (order swapped) | Overwrites your source | Destination first |
| Destination too small for strcat | Buffer overflow, crash | Size ≥ len1 + len2 + 1 |
Forgetting #include <string.h> | Implicit declaration warning/error | Include the header |
String Functions Practice Questions
- What is the output of
strlen("Hello World")? - What does
strcmpreturn if both strings are equal? - Why can't we compare strings using
==? - What is the minimum size of
destforstrcpy(dest, "C Lang")? - Is
strreva standard C function?
Show answers
- 11 (the space counts).
- 0.
==compares the addresses of the two arrays, not their characters.- 7 bytes (6 characters +
'\0'). - No. It exists only in some old compilers like Turbo C.
Coding Exercise
Using strcmp, find which of the three names "Meera", "Aman", "Kiran" comes first in dictionary order, then print a greeting made with strcpy and strcat: "Welcome, Aman".
Show solution
#include <stdio.h>
#include <string.h>
int main(void)
{
char a[] = "Meera", b[] = "Aman", c[] = "Kiran";
char first[10], msg[30];
strcpy(first, a);
if (strcmp(b, first) < 0)
strcpy(first, b);
if (strcmp(c, first) < 0)
strcpy(first, c);
strcpy(msg, "Welcome, ");
strcat(msg, first);
printf("%s\n", msg);
return 0;
}
Welcome, Aman
Quick Quiz: String Functions in C (MCQ)
-
Header file for string functions:
A)
stdio.hB)string.hC)stdlib.hD)ctype.h -
strlen("C\0Lang")returns:A) 6 B) 5 C) 1 D) 0
-
strcmp("abc", "abd")returns:A) 0 B) A positive value C) A negative value D) 1 always
-
Which joins two strings?
A)
strcpyB)strcatC)strcmpD)strlen -
In
strcpy(a, b), the data is copied:A) From a to b B) From b to a C) Both ways D) Nowhere
Show answers
- B:
string.h. - C: 1 (it stops at the first
'\0'). - C: negative ('c' < 'd').
- B:
strcat. - B: from b to a.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Header | <string.h> |
|---|---|
| strlen | Length, without '\0' |
| strcpy(d, s) | Copy s into d: destination first |
| strcat(d, s) | Append s to end of d |
| strcmp = 0 | Strings equal |
| strcmp < 0 / > 0 | s1 before / after s2 |
| Not standard | strrev, strupr, strlwr |
Frequently asked questions
- What is the difference between strlen and sizeof?
- strlen counts characters before '\0' at run time; sizeof gives the whole array size in bytes.
- How do you compare two strings in C?
- Use strcmp(s1, s2) == 0;
==only compares addresses. - What does strcmp return?
- 0 if equal, negative if s1 comes first, positive if s1 comes later.
Remember
- len, copy, cat, cmp: the big four.
- Copy and cat work like dest = src.
Next Topic
Next lesson: String Operations Without string.h. You will write your own strlen, strcpy, strcat, reverse and palindrome check without string.h.