Back to course

Standard String Library Functions

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 31: Standard String Library Functions

To manipulate strings, you must include the <string.h> header file. These functions are critical for C programming.

1. Finding Length: strlen()

Returns the number of characters in the string, excluding the null terminator (\0).

c #include <string.h>

char str[] = "Code"; size_t len = strlen(str); // len is 4

2. Copying Strings: strcpy()

Copies the source string into the destination array. Warning: The destination array must be large enough to hold the source string plus the null terminator.

c char src[] = "Hello"; char dest[10]; strcpy(dest, src); // dest now contains "Hello"

3. Concatenation (Joining): strcat()

Appends the source string to the end of the destination string.

c char first[20] = "C "; char last[] = "Programming"; strcat(first, last); // first now contains "C Programming"

4. Comparison: strcmp()

Compares two strings lexicographically (alphabetically).

  • Returns 0 if the strings are identical.
  • Returns a negative value if string 1 comes before string 2.
  • Returns a positive value if string 1 comes after string 2.

c char s1[] = "apple"; char s2[] = "banana";

if (strcmp(s1, s2) == 0) { printf("Strings are equal.\n"); }

Secure Alternatives: For functions like strcpy and strcat, secure alternatives like strncpy and strncat (which take a size argument) are often preferred to prevent buffer overflows.