strncmp 是 C 语言中的一个标准库函数,用于比较两个字符串的前 n 个字符。此函数是 头文件的一部分。
int strncmp(const char *str1, const char *str2, size_t n);
str1 和 str2:要比较的两个字符串。n:要比较的最大字符数。str1 和 str2 的前 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
#include
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 是 C 语言中的一个标准库函数,用于复制一个字符串的前 n 个字符到另一个字符串中。如果源字符串的长度小于 n,则目标字符串的其余部分将用空字符 ('\0') 填充。此函数是 头文件的一部分。
char *strncpy(char *dest, const char *src, size_t n);
dest: 目标字符串,即复制的内容将被放置的位置。src: 源字符串,即从中复制内容的字符串。n: 要复制的最大字符数。dest 的指针。src 的长度小于 n,则 dest 中的剩余部分将被空字符填充。src 的长度大于或等于 n,则结果将不会以空字符结尾。dest 完整的字符串以空字符结束,使用者可能需要手动设置 dest[n] = '\0'。#include
#include
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 会包括原始字符串的空字符。