C- strncmp() & strncpy()

strncmp()

strncmp 是 C 语言中的一个标准库函数,用于比较两个字符串的前 n 个字符。此函数是 <string.h> 头文件的一部分。

函数原型:

int strncmp(const char *str1, const char *str2, size_t n);

参数:

  • str1str2:要比较的两个字符串。
  • n:要比较的最大字符数。

返回值:

  • 如果 str1str2 的前 n 个字符完全相同,返回 0。
  • 如果 str1 的前 n 个字符在字典上小于 str2 的前 n 个字符,返回一个负整数。
  • 如果 str1 的前 n 个字符在字典上大于 str2 的前 n 个字符,返回一个正整数。

注意:

  • strncmp 在比较时是按字典顺序进行的,而不仅仅是基于字符的 ASCII 值。
  • n 为 0 时,函数返回 0。
  • strncmp 在遇到字符串的终止符 ('\0') 之前最多比较 n 个字符,这意味着如果两个字符串的前 n 个字符相同,但是其中一个在前 n 个字符之前就结束了(例如 "abc""abcdef"n=3 时),那么它们被视为相等。

示例:

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

int main() {
    
    
    char str1[] = "apple";
    char str2[] = "application";

    int result = strncmp(str1, str2, 4);

    if(result == 0) {
    
    
        printf("The first 4 characters of both strings are the same.\n");
    } else if(result < 0) {
    
    
        printf("The first 4 characters of str1 come before str2 in dictionary order.\n");
    } else {
    
    
        printf("The first 4 characters of str1 come after str2 in dictionary order.\n");
    }

    return 0;
}

上述代码将输出:“The first 4 characters of both strings are the same.”因为 “apple” 和 “application” 的前四个字符是一样的。

strncpy()

strncpy 是 C 语言中的一个标准库函数,用于复制一个字符串的前 n 个字符到另一个字符串中。如果源字符串的长度小于 n,则目标字符串的其余部分将用空字符 ('\0') 填充。此函数是 <string.h> 头文件的一部分。

函数原型:

char *strncpy(char *dest, const char *src, size_t n);

参数:

  • dest: 目标字符串,即复制的内容将被放置的位置。
  • src: 源字符串,即从中复制内容的字符串。
  • n: 要复制的最大字符数。

返回值:

  • 返回一个指向目标字符串 dest 的指针。

注意事项:

  1. 如果 src 的长度小于 n,则 dest 中的剩余部分将被空字符填充。
  2. 如果 src 的长度大于或等于 n,则结果将不会以空字符结尾。
  3. 为了确保 dest 完整的字符串以空字符结束,使用者可能需要手动设置 dest[n] = '\0'

示例:

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

int main() {
    
    
    char src[] = "Hello, World!";
    char dest[15];

    strncpy(dest, src, 14); // Copies 14 characters from `src` to `dest`

    printf("Source: %s\n", src);
    printf("Destination: %s\n", dest);

    return 0;
}

在上述代码中,源字符串 “Hello, World!” 的 14 个字符(包括空字符)被复制到目标字符串 dest 中。结果 dest 也是一个完整的 C 字符串,因为 strncpy 会包括原始字符串的空字符。

猜你喜欢

转载自blog.csdn.net/weixin_43844521/article/details/133268577