Of course! The C language provides a standard library for handling strings, which are essentially arrays of characters terminated by a null character ('\0'). This library is part of the <string.h> header file.

Here's a comprehensive guide to the C string library, covering the most common functions, their usage, and important best practices.
Including the String Library
Before you can use any of these functions, you must include the header file at the top of your C source file:
#include <string.h>
The Core Concept: Null-Termination
In C, a string is not a special data type like in other languages (e.g., String in Java or str in Python). It's simply a character array where the last character is always the null terminator (\0). This special character tells functions where the string ends.
Example:

char greeting[] = "Hello"; // The compiler automatically adds '\0' at the end.
// The array in memory looks like: {'H', 'e', 'l', 'l', 'o', '\0'}
Essential String Functions
These are the functions you'll use most frequently. I'll provide a description, the function signature, a simple example, and a "Gotcha" section for common pitfalls.
a. strlen() - String Length
-
Purpose: Calculates the length of a string (the number of characters before the null terminator).
-
Signature:
size_t strlen(const char *str); -
Return Value: The length of the string as a
size_t(an unsigned integer type).
(图片来源网络,侵删) -
Example:
#include <stdio.h> #include <string.h> int main() { char text[] = "Hello, World!"; size_t length = strlen(text); printf("The length of '%s' is %zu\n", text, length); // Output: The length of 'Hello, World!' is 13 return 0; } -
Gotcha:
strlenstarts at the beginning of the string and scans memory until it finds a'\0'. If you forget to null-terminate your character array,strlenwill keep reading past the end of the array, leading to undefined behavior (often a crash or garbage output).
b. strcpy() - String Copy
-
Purpose: Copies the source string to the destination string.
-
Signature:
char *strcpy(char *dest, const char *src); -
Return Value: A pointer to the destination string (
dest). -
Example:
#include <stdio.h> #include <string.h> int main() { char source[] = "Copy this!"; char destination[20]; // Must be large enough to hold the source + '\0' strcpy(destination, source); printf("Destination: %s\n", destination); // Output: Destination: Copy this! return 0; } -
Gotcha:
strcpydoes NOT check if the destination array has enough space. It will happily copy past the end ofdestination, causing a buffer overflow, which is a major security risk. Always ensuredestis large enough.
c. strncpy() - Safer String Copy
-
Purpose: A safer version of
strcpythat limits the number of characters to copy. -
Signature:
char *strncpy(char *dest, const char *src, size_t n); -
Return Value: A pointer to the destination string (
dest). -
Example:
#include <stdio.h> #include <string.h> int main() { char source[] = "Hello"; char destination[10]; strncpy(destination, source, 3); // Copy only 3 characters printf("Destination (copy 3): %s\n", destination); // Output: Destination (copy 3): Hel // Important: strncpy does not guarantee null-termination if the source is longer than n char source2[] = "A very long string"; char dest2[5]; strncpy(dest2, source2, 4); // Copies 'A', ' ', 'v', 'e' dest2[4] = '\0'; // YOU must manually add the null terminator! printf("Destination (manual null-term): %s\n", dest2); // Output: Destination (manual null-term): A ve return 0; } -
Gotcha: If the length of
srcis greater than or equal ton,strncpywill not add the null terminator todest. You are responsible for adding it yourself to avoid futurestrlenorprintferrors.
d. strcat() - String Concatenation (Append)
-
Purpose: Appends the source string to the end of the destination string.
-
Signature:
char *strcat(char *dest, const char *src); -
Return Value: A pointer to the destination string (
dest). -
Example:
#include <stdio.h> #include <string.h> int main() { char str1[20] = "Hello, "; char str2[] = "World!"; strcat(str1, str2); printf("Concatenated: %s\n", str1); // Output: Concatenated: Hello, World! return 0; } -
Gotcha: Like
strcpy,strcatdoes not check for buffer overflow. The destination (dest) must have enough free space to hold its own content plus the entire source string (src) plus the new null terminator.
e. strncat() - Safer String Concatenation
-
Purpose: Appends up to
ncharacters from the source string to the destination. -
Signature:
char *strncat(char *dest, const char *src, size_t n); -
Return Value: A pointer to the destination string (
dest). -
Example:
#include <stdio.h> #include <string.h> int main() { char str1[20] = "Hello, "; char str2[] = "World!"; strncat(str1, str2, 3); // Append only "Wor" printf("Concatenated (3 chars): %s\n", str1); // Output: Concatenated (3 chars): Hello, Wor // strncat is safer because it guarantees null-termination char str3[10] = "Start"; char str4[] = "Finish"; strncat(str3, str4, 5); // str3 has space for "Start" + 5 more chars + '\0' printf("Safe concatenation: %s\n", str3); // Output: Safe concatenation: StartFinish return 0; } -
Gotcha:
strncatwill always add a null terminator, which is good. However, it's still possible to overflow the buffer ifdestdoesn't have enough space forstrlen(dest) + n + 1. It's safer to calculate the required space.
f. strcmp() - String Comparison
-
Purpose: Compares two lexicographically (dictionary order).
-
Signature:
int strcmp(const char *s1, const char *s2); -
Return Value:
- Negative value: if
s1is less thans2. - Zero: if
s1is equal tos2. - Positive value: if
s1is greater thans2.
- Negative value: if
-
Example:
#include <stdio.h> #include <string.h> int main() { char str_a[] = "apple"; char str_b[] = "banana"; char str_c[] = "apple"; printf("apple vs banana: %d\n", strcmp(str_a, str_b)); // Output: apple vs banana: -1 (or a negative number) printf("banana vs apple: %d\n", strcmp(str_b, str_a)); // Output: banana vs apple: 1 (or a positive number) printf("apple vs apple: %d\n", strcmp(str_a, str_c)); // Output: apple vs apple: 0 return 0; } -
Gotcha: Do not use
strcmpfor comparing numbers.strcmp("10", "2")will return a negative value because '1' comes before '2' in ASCII, which is not numerical comparison. Useatoiorstrtolfor that.
g. strncmp() - Limited String Comparison
-
Purpose: Compares only the first
ncharacters of two strings. -
Signature:
int strncmp(const char *s1, const char *s2, size_t n); -
Return Value: Same as
strcmp. -
Example:
#include <stdio.h> #include <string.h> int main() { char str_a[] = "apple pie"; char str_b[] = "apple sauce"; // Compare only the first 5 characters if (strncmp(str_a, str_b, 5) == 0) { printf("The first 5 characters are the same.\n"); // This will be printed } else { printf("The first 5 characters are different.\n"); } return 0; }
Modern and Safer Alternatives (C11 and later)
The C standard introduced a new set of functions that are safer and more robust. They take the size of the destination buffer as an argument, preventing buffer overflows.
| Old Function | New Safer Function | Description |
|---|---|---|
strcpy(dest, src) |
strncpy_s(dest, dsize, src, ssize) |
Copies src to dest. dsize is the size of dest. ssize is the max chars to copy. |
strcat(dest, src) |
strncat_s(dest, dsize, src, ssize) |
Appends src to dest. dsize is the total size of dest. |
sprintf(buf, ...) |
sprintf_s(buf, size, ...) |
Formatted printing into a buffer. size is the buffer's size. |
scanf(...) |
scanf_s(...) |
Formatted input. Requires specifying the size for c, s, and [ format specifiers. |
Example with strncpy_s:
#include <stdio.h>
#include <string.h> // Note: strncpy_s is in <string.h>
int main() {
char destination[5]; // Small buffer
char source[] = "This is a very long string";
// strncpy_s is safe. It will not copy more than 4 characters
// (destination size - 1 for the null terminator).
// It also guarantees null-termination.
strncpy_s(destination, sizeof(destination), source, sizeof(destination) - 1);
printf("Destination: %s\n", destination); // Output: Destination: This
return 0;
}
Note: These safer functions are part of the C11 standard. Not all compilers (especially older ones or embedded systems) support them. For maximum portability, the classic functions are more common, but you must be extremely careful.
Summary Table
| Function | Purpose | Key Consideration |
|---|---|---|
strlen |
Get string length | Requires a valid null-terminated string. |
strcpy |
Copy a string | Unsafe. Ensure destination is large enough. |
strncpy |
Copy up to n chars |
Safer, but not foolproof. May not null-terminate. |
strcat |
Append a string | Unsafe. Ensure destination has enough space. |
strncat |
Append up to n chars |
Safer. Guarantees null-termination. |
strcmp |
Compare two strings | Returns negative, zero, or positive. Not for numbers. |
strncmp |
Compare first n chars |
Same as strcmp, but limited. |
strncpy_s |
Safe copy | Modern C11. Takes buffer size to prevent overflow. |
