Nearby lessons
45 of 72C - String Functions
C provides useful string functions through the string.h header file. Learn how to find string length, copy strings, join strings, and compare strings using simple examples.
Introduction to String Functions
C provides ready-made functions to perform common string operations.
To use these functions, include the string.h header file.
strlen()- Finds the length of a string.strcpy()- Copies one string into another.strcat()- Joins two strings.strcmp()- Compares two strings.
strlen() - Find String Length
The strlen() function counts the characters in a string. It does not count the ending null character.
strcpy() - Copy a String
The strcpy() function copies the contents of one string into another character array.
The destination array must have enough space to store the copied string, including the null character.
strcat() - Join Two Strings
The strcat() function adds the second string to the end of the first string.
The first array must have enough space for both strings and the ending null character.
strcmp() - Compare Two Strings
The strcmp() function compares two strings.
- It returns
0when both strings are equal. - It returns a negative value or a positive value when the strings differ.
Use strcmp() instead of == when comparing string contents.
Using Multiple String Functions
We can use different string functions in the same program.
Common Mistakes
- Forgetting to include
#include <string.h>. - Using a destination array that is too small for
strcpy(). - Using a destination array that is too small for
strcat(). - Using
==to compare string contents instead ofstrcmp(). - Thinking
strlen()counts the ending null character. It does not.
- Include <string.h> to use these string functions.
- strlen() finds the number of characters in a string.
- strcpy() copies one string into another array.
- strcat() joins two strings.
- strcmp() compares two strings.