Back to C Programming
2026-07-136 min read

Commonly used library functions to work with strings

Learn Commonly used library functions to work with strings step by step with clear examples and exercises.

Why This Matters

In this extensive guide, we will explore the commonly used library functions for working with strings in C programming. We'll delve into why these functions are indispensable, their prerequisites, a detailed core concept explanation, a worked example, common mistakes to avoid, practice questions, and frequently asked questions. Let's embark on this journey!

Why This Matters

Manipulating strings is crucial in C programming for creating dynamic, user-friendly applications. However, string manipulation can be complex without the support of library functions. These functions simplify the process, making your code more efficient and readable. Understanding these functions will help you write robust programs, prepare for interviews, and even debug real-world issues.

Prerequisites

Before diving into string manipulation functions, it is essential to have a strong understanding of:

  1. C programming basics, including variables, data types, operators, control structures, and arrays.
  2. Basic file I/O operations in C.
  3. Understanding pointers and their role in handling strings.
  4. Familiarity with memory management concepts, such as dynamic memory allocation and deallocation.

Core Concept

The string handling library in C is string.h. This library provides various functions to perform common string manipulations, such as concatenation, comparison, searching, and replacement. Here are some of the most commonly used string functions:

  1. strlen(char *str) - Returns the length of a given string.
  2. strcmp(char *str1, char *str2) - Compares two strings lexicographically (alphabetically).
  3. strcpy(char *dest, const char *src) - Copies the source string to the destination string.
  4. strcat(char *dest, const char *src) - Concatenates the source string to the end of the destination string.
  5. strncat(char *dest, const char *src, size_t n) - Similar to strcat, but limits the number of characters copied from the source string (n).
  6. strchr(const char *str, int c) - Searches for the first occurrence of a specified character in a string.
  7. strrchr(const char *str, int c) - Searches for the last occurrence of a specified character in a string.
  8. strstr(const char *haystack, const char *needle) - Searches for the first occurrence of a substring within another string.
  9. memset(void *ptr, int value, size_t num) - Sets a block of memory to a specific value. This function can be used to initialize a string with a specific character or clear a string.
  10. memcpy(void *dest, const void *src, size_t n) - Copies a specified number of bytes from the source to the destination. This function can be used to copy one string to another.
  11. strncmp(const char *str1, const char *str2, size_t n) - Compares two strings up to a specified number of characters (n).
  12. strdup(const char *str) - Returns a duplicate of the input string, dynamically allocating memory for it.
  13. memchr(const void *s, int c, size_t n) - Searches for the first occurrence of a specified character in a block of memory (similar to strchr, but can search through arbitrary blocks of memory).

Worked Example

Let's create a simple C program that demonstrates some of these functions:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
char *str1 = "Hello, World!";
char *str2;
int len;

printf("Original string: %s\n", str1);

// Find the length of the string
len = strlen(str1);
printf("Length of the string: %d\n", len);

// Allocate memory for a copy of the string
str2 = (char *)malloc((len + 1) * sizeof(char));
if (str2 == NULL) {
perror("Memory allocation error");
return 1;
}

// Copy the string to the new memory location
strcpy(str2, str1);
printf("Copied string: %s\n", str2);

// Concatenate two strings
char *concat = (char *)malloc((len + strlen(" This is a test.") + 1) * sizeof(char));
if (concat == NULL) {
perror("Memory allocation error");
return 1;
}
strcpy(concat, str2);
strcat(concat, " This is a test.");
printf("Concatenated string: %s\n", concat);

// Search for the first occurrence of 'l' in the original string
char *pos = strchr(str1, 'l');
if (pos != NULL) {
printf("First occurrence of 'l': %c\n", *pos);
} else {
printf("No occurrences of 'l' found.\n");
}

// Free allocated memory
free(str2);
free(concat);

return 0;
}

Common Mistakes

  1. Forgetting to include the string.h library.
  2. Passing incorrect data types as arguments to string functions (e.g., passing a char array instead of a pointer to a char array).
  3. Not checking for null pointers before using them with string functions.
  4. Overflowing strings by not considering their capacity when concatenating or copying.
  5. Using strcpy without ensuring there is enough space in the destination string (either by dynamically allocating memory or checking the size of the destination array).
  6. Failing to free dynamically allocated memory after use.
  7. Not handling cases where memory allocation fails gracefully (e.g., returning an error code, printing an error message, and exiting the program).
  8. Using strncpy without properly setting the terminating null character if the source string is shorter than the destination size.
  9. Comparing strings with == instead of using strcmp.
  10. Misunderstanding the difference between strcat, strncat, and strlcat (the latter being a safer alternative that prevents buffer overflow).

Practice Questions

  1. Write a program that reverses a given string using the strlen, strchr, and memcpy functions, and dynamically allocating memory for the reversed string.
  2. Create a program that checks if two strings are anagrams (i.e., they contain the same letters, but possibly in a different order).
  3. Write a function that finds the number of occurrences of a substring within another string using the strlen, strchr, and strncmp functions.
  4. Modify the worked example to handle cases where memory allocation fails gracefully.
  5. Implement a function that concatenates two strings without using any library functions (only basic C operations).
  6. Write a program that sorts an array of strings lexicographically using the bubble sort algorithm and the strcmp function.
  7. Create a program that counts the number of words in a given string, where a word is defined as a sequence of non-whitespace characters.
  8. Implement a function that finds the longest common substring between two strings using dynamic programming and the strlen function.
  9. Write a program that replaces all occurrences of a specified character within a string using the strlen, strchr, and memcpy functions.
  10. Create a program that removes duplicates from an array of strings, sorting the resulting unique strings lexicographically using the strcmp function.

FAQ

What is the difference between strcpy and strncpy?

strcpy copies the entire source string to the destination, while strncpy limits the number of characters copied based on a specified size (n). If the source string is shorter than the destination size, strncpy may not null-terminate the destination string properly.

Why should I use strncat instead of strcat?

Using strncat prevents buffer overflow by limiting the number of characters copied from the source string, ensuring that the destination array does not exceed its capacity.

What is a null-terminated string in C?

A null-terminated string in C is a sequence of characters ending with a null character (\0). This allows easy manipulation and detection of string length using functions like strlen.

What is the difference between strlcat and strncat?

strlcat is a safer alternative to strncat that prevents buffer overflow by taking into account the size of the destination string, including the null terminator.

Why should I use memchr instead of strchr?

memchr can search for a character within an arbitrary block of memory, not just strings. This makes it more versatile when dealing with non-string data types.

What is the difference between strcmp, strncmp, and memcmp?

strcmp compares two null-terminated strings lexicographically, while strncmp compares up to a specified number of characters (n) from each string. memcmp compares two blocks of memory of equal size byte by byte.

What is the difference between strdup and malloc?

strdup dynamically allocates memory for a duplicate of a given string, including space for the null terminator. malloc only allocates raw memory without considering the string's structure.