The standard C library provides the <string.h> header file, which contains essential functions for performing operations on null-terminated character arrays (strings).
1. Calculating Length (strlen)
The strlen() function calculates the length of a string by counting the number of characters before the terminating null character (\0).
Syntax: size_t strlen(const char *s);
#include <string.h>
char name[] = "Dennis";
int len = strlen(name);
printf("Length of string: %d\n", len); // Output: 6
2. Copying Strings (strcpy and strncpy)
You cannot use the assignment operator (=) to copy string contents. You must use a function to copy the characters from the source to the destination array.
A. Copy Full String (strcpy)
The strcpy() function copies the entire string, including the null terminator, from the source array to the destination array.
- Requirement: The destination array must be large enough to hold the source string plus its null terminator.
Syntax: char *strcpy(char *dest, const char *src);
char source[] = "Copy me!";
char destination[20]; // Ensure enough space
strcpy(destination, source);
printf("Copied string: %s\n", destination);
B. Copy N Characters (strncpy)
The strncpy() function copies only the specified number of characters (n).
- Caution: If the source string is shorter than
n, null characters are padded. If the source string is longer thann, the resulting destination string will not be null-terminated, leading to potential errors.
Syntax: char *strncpy(char *dest, const char *src, size_t n);
3. Concatenating Strings (strcat and strncat)
Concatenation means joining two strings end-to-end.
A. Concatenate Full String (strcat)
The strcat() function appends the source string to the end of the destination string.
- Requirement: The destination array must have sufficient extra space to hold the entire source string.
Syntax: char *strcat(char *dest, const char *src);
char s1[50] = "Hello, "; // Destination MUST be large enough
char s2[] = "World!";
strcat(s1, s2);
printf("Concatenated: %s\n", s1); // Output: Hello, World!
B. Concatenate N Characters (strncat)
The strncat() function is safer as it only appends a specified number of characters (n) and always adds a null terminator to the result.
Syntax: char *strncat(char *dest, const char *src, size_t n);
4. Comparing Strings (strcmp)
The strcmp() function compares two strings lexicographically (alphabetically, based on ASCII values).
Syntax: int strcmp(const char *s1, const char *s2);
| Return Value | Meaning |
| 0 | The strings are identical. |
| Negative | s1 comes before s2 alphabetically. |
| Positive | s1 comes after s2 alphabetically. |
Comparison Example
char strA[] = "apple";
char strB[] = "banana";
if (strcmp(strA, strB) < 0) {
printf("%s comes first.\n", strA); // This executes
}
