Nearby lessons

45 of 72

C - 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.
Example01
Loading editor…

strlen() - Find String Length

The strlen() function counts the characters in a string. It does not count the ending null character.

Example02
Loading editor…

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.

Example03
Loading editor…

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.

Example04
Loading editor…

strcmp() - Compare Two Strings

The strcmp() function compares two strings.

  • It returns 0 when 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.

Example05
Loading editor…

Using Multiple String Functions

We can use different string functions in the same program.

Example06
Loading editor…

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 of strcmp().
  • Thinking strlen() counts the ending null character. It does not.
📝 Key Takeaways
  • 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.

🧠 Test Your Knowledge

5 Questions
Progress: 0 / 5

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.