String Handling Functions in C: strlen, strcpy, and More
In C, strings are stored as arrays of characters and are terminated by a null character <span>'\0'</span>
. To facilitate the manipulation and processing of strings, the C standard library provides a series of string handling functions. In this article, we will detail several commonly used string handling functions, including <span>strlen</span>
, <span>strcpy</span>
, <span>strcat</span>
, and <span>strcmp</span>
, and demonstrate their usage through example code.
1. strlen Function
Functionality
<span>strlen</span>
function is used to calculate the length of a string, returning the number of characters excluding the terminating character <span>'\0'</span>
.
Prototype
size_t strlen(const char *str);
Example Code
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "Hello, World!";
size_t length = strlen(str);
printf("The length of the string is: %zu\n", length);
return 0;
}
Explanation
In the example, we declare a string containing the text “Hello, World!” and then use the <span>strlen()</span>
function to obtain its length and print the result.
2. strcpy Function
Functionality
<span>strcpy</span>
function is used to copy the source string to the destination character array.
Prototype
char *strcpy(char *dest, const char *src);
Example Code
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello, World!";
char dest[50]; // Ensure the destination array is large enough to hold the source array
strcpy(dest, src); // Copy data from src to dest
printf("Source: %s\n", src);
printf("Destination: %s\n", dest);
return 0;
}
Explanation
This program copies “Hello, World!” from the source character array to the destination character array. It is important to note that the destination must have enough space to hold the copied data, including the terminating null character.
3. strcat Function
Functionality
<span>strcat()</span>
is used to concatenate two strings, appending the string pointed to by the second argument to the end of the first argument.