Back to C Programming
2026-03-026 min read

Strings library (C Programming)

Learn Strings library (C Programming) step by step with clear examples and exercises.

Title: Mastering C's String Library: A full guide for Practical Programming

Why This Matters

In C programming, manipulating strings is a common task that you'll encounter in various scenarios such as coding interviews, real-world projects, and academic assignments. Understanding the string library in C can help you write efficient, error-free code and solve complex problems with ease. The ability to handle strings effectively is crucial for working with text data, which is an essential aspect of many applications. This guide will provide a comprehensive understanding of C's string library functions, their usage, common pitfalls to avoid, and best practices for optimizing your code.

Prerequisites

Before diving into the world of strings in C, it's essential to have a solid foundation in:

  1. Basic C syntax and data structures (variables, arrays, pointers)
  2. File input/output using stdio.h library
  3. Understanding memory allocation and deallocation functions like malloc(), calloc(), free(), etc.
  4. Functions and function declarations
  5. Data types (int, char, float, double)
  6. Control structures (if-else statements, loops)
  7. Basic input/output operations (printf(), scanf())
  8. Regular expressions (optional but useful for email validation)

Core Concept

Introduction to C's String Library

The string library in C provides a set of functions for handling strings, making it easier to manipulate text data. The string library is declared in the header file string.h. Some essential functions included are:

  • strlen(): returns the length of a string
  • strcpy(): copies the source string into the destination string
  • strcmp(): compares two strings and returns the difference between them (0 if equal)
  • strcat(): concatenates two strings
  • strchr(): locates a specific character within a string
  • strspn(): finds the length of an initial segment common to two strings
  • strpbrk(): searches for any of a set of characters in a string
  • memset(): sets all bytes of the string to a specified value
  • memcpy(): copies a block of memory

Working with Null-terminated Byte Strings

In C, strings are represented as arrays of characters, where the last character is always a null character (\0). This convention allows the program to determine the string's length easily.

char str[] = "Hello, World!";
printf("%d", strlen(str)); // Output: 13 (including the null terminator)

String Manipulation with Examples

Copying Strings using strcpy()

char src[] = "Source string";
char dest[50];
strcpy(dest, src); // Copies the source string into the destination string
printf("%s\n", dest); // Output: Source string

Comparing Strings using strcmp()

char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2); // Compares the two strings and returns 26 (ASCII difference between 'H' and 'W')
if (result == 0) {
printf("Strings are equal.\n");
} else {
printf("Strings are not equal.\n");
}

Concatenating Strings using strcat()

char str1[] = "Hello";
char str2[] = " World!";
char result[50];
strcat(str1, str2); // Concatenates the two strings and stores the result in a new string
printf("%s\n", str1); // Output: Hello World!

Worked Example

Example 1: Reversing a String using strlen(), strcpy(), and strrev()

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

void reverseString(char *str) {
char revStr[50];
int len = strlen(str);
for (int i = 0; i < len; i++) {
revStr[(len - 1) - i] = str[i]; // Reversing the string
}
printf("Reversed String: %s\n", revStr);
}

int main() {
char str[] = "Hello, World!";
reverseString(str);
return 0;
}

How It Works Internally

The string library functions in C are implemented using various techniques such as pointers and memory allocation. For example, the strlen() function iterates through the string until it finds the null terminator, while the strcpy() function copies characters from the source string to the destination string. The specific implementation details can vary depending on the compiler and operating system.

Common Mistakes

Forgetting the Null Terminator

When dynamically allocating memory for a string and not including the null terminator, you may encounter unexpected behavior.

char *str;
str = (char*)malloc(5); // Allocates memory for 5 characters
str[0] = 'H'; str[1] = 'e'; str[2] = 'l'; str[3] = 'l'; str[4] = '\0'; // Incorrectly initializing the null terminator

Buffer Overflow

Buffer overflow occurs when you write beyond the allocated memory for a string. This can lead to undefined behavior and security vulnerabilities.

char str[5];
strcpy(str, "HelloWorld"); // Copies "HelloWorld" into str (buffer overflow)

Incorrect Use of strcmp()

Comparing strings with == instead of using the strcmp() function can lead to unexpected results.

char str1[] = "Hello";
char str2[] = "World";
if (str1 == str2) { // Incorrect comparison
printf("Strings are equal.\n");
}

Not Checking Return Values

Some functions in the string library return values that indicate success or failure. Failing to check these return values can result in incorrect program behavior.

char str1[5] = "Hello";
char str2[5];
strcpy(str2, str1); // Copies "Hello" into str2 (no space for the null terminator)
if (strlen(str2) == 5) { // Checking the return value of strlen()
printf("Strings copied successfully.\n");
} else {
printf("Insufficient memory for string copy.\n");
}

Practice Questions

Question 1: Write a program that counts the number of occurrences of each vowel in a given string.

Question 2: Implement a function that finds the longest common substring between two strings using C's string library functions.

FAQ

How can I reverse a string using C's string library functions?

You can reverse a string in C by manually iterating through the string and swapping characters from both ends. Here's an example:

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

void reverseString(char *str) {
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
printf("%s\n", str); // Output: reversed string
}

int main() {
char str[] = "ABCDEFGHIG";
reverseString(str);
return 0;
}

How can I find the longest common substring between two strings?

To find the longest common substring between two strings, you can implement a dynamic programming solution using a 2D array. Here's an example:

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

int lcs(char *str1, char *str2, int m, int n) {
int dp[m + 1][n + 1];
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0)
dp[i][j] = 0;
else if (str1[i - 1] == str2[j - 1])
dp[i][j] = dp[i - 1][j - 1] + 1;
else
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
return dp[m][n]; // Returns the length of the longest common substring
}

int main() {
char str1[] = "ABCBDAB";
char str2[] = "BDCABA";
printf("%d\n", lcs(str1, str2, strlen(str1), strlen(str2))); // Output: 4 (common substring: "BCDA")
return 0;
}

How can I remove all duplicate characters from a string and return the result as a new string?

To remove all duplicate characters from a string and return the result as a new string, you can use a hash table or an array to store unique characters. Here's an example using an array:

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

void removeDuplicates(char *str) {
int arr[256] = {0}; // Initialize an array to store character counts
int index = 0;
for (int i = 0; str[i]; i++) {
if (!arr[str[i]]) {
arr[str[i]] = 1;
str[index++] = str[i]; // Move unique characters to the beginning of the array
}
}
// Add a null terminator and copy the unique characters into a new string
str[index] = '\0';
char result[index + 1];
for (int i = 0; i < index; i++) {
result[i] = str[i];
}
printf("%s\n", result); // Output: unique string without duplicates
}

int main() {
char str[] = "ABCDEFGHIG";
removeDuplicates(str);
return 0;
}