C语言string库常用函数有哪些?

99ANYc3cd6
预计阅读时长 37 分钟
位置: 首页 C语言 正文

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.

c语言string library
(图片来源网络,侵删)

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:

c语言string library
(图片来源网络,侵删)
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).

    c语言string library
    (图片来源网络,侵删)
  • 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: strlen starts at the beginning of the string and scans memory until it finds a '\0'. If you forget to null-terminate your character array, strlen will 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: strcpy does NOT check if the destination array has enough space. It will happily copy past the end of destination, causing a buffer overflow, which is a major security risk. Always ensure dest is large enough.

c. strncpy() - Safer String Copy

  • Purpose: A safer version of strcpy that 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 src is greater than or equal to n, strncpy will not add the null terminator to dest. You are responsible for adding it yourself to avoid future strlen or printf errors.

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, strcat does 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 n characters 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: strncat will always add a null terminator, which is good. However, it's still possible to overflow the buffer if dest doesn't have enough space for strlen(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 s1 is less than s2.
    • Zero: if s1 is equal to s2.
    • Positive value: if s1 is greater than s2.
  • 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 strcmp for comparing numbers. strcmp("10", "2") will return a negative value because '1' comes before '2' in ASCII, which is not numerical comparison. Use atoi or strtol for that.

g. strncmp() - Limited String Comparison

  • Purpose: Compares only the first n characters 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.
-- 展开阅读全文 --
头像
Linux C语言中sysinfo如何获取系统信息?
« 上一篇 12-07
dede文章自定义文件名是哪个字段名
下一篇 » 12-07

相关文章

取消
微信二维码
支付宝二维码

目录[+]