再学C语言50:C库中的字符串函数(2)
一、strcmp()函数
功能:对字符串内容进行比较,如果两个字符串参数相同,函数返回0
示例代码:
/* test of strcmp() function */
#include <stdio.h>
#include <string.h>#define NAME "Forster"int main(void)
{char arr[100];printf("guess my name:\\n");gets(arr);while(strcmp(arr, NAME) != 0){puts("Wrong, guess again:");gets(arr);}puts("Right!");return 0;
}
运行结果:
strcmp()函数比较的是字符串,而不是数组;虽然arr占用100个内存单元,而“Forster”只占用8个内存单元(一个用来存放空字符),但是函数在比较时只看arr的第一个空字符之前的部分;因此,strcmp()函数可以用来比较存放在不同大小数组里的字符串
strcmp()函数的返回值:
strcmp()函数中,对两个字符串的所有字符按照顺序逐个比较,按照机器编码顺序进行比较,字符的比较根据的是它们的数字表示法,一般是ASCII值
如果第一个字符串在字母表中的顺序落后于第二个字符串,返回一个正数;如果第一个字符串在字母表中的顺序领先于第二个字符串,返回一个负数
确切的比较依赖于不同的C实现
示例代码:
/* test return value of strcmp() function */
#include <stdio.h>
#include <string.h>int main(void)
{printf("strcmp(\\"A\\", \\"A\\") is ");printf("%d\\n", strcmp("A", "A"));printf("strcmp(\\"A\\", \\"B\\") is ");printf("%d\\n", strcmp("A", "B"));printf("strcmp(\\"B\\", \\"A\\") is ");printf("%d\\n", strcmp("B", "A"));printf("strcmp(\\"Apple\\", \\"A\\") is ");printf("%d\\n", strcmp("Apple", "A"));printf("strcmp(\\"A\\", \\"Apple\\") is ");printf("%d\\n", strcmp("A", "Apple"));printf("strcmp(\\"Apple\\", \\"Apples\\") is ");printf("%d\\n", strcmp("Apple", "Apples"));return 0;
}
运行结果:
二、strncmp()函数
strcmp()函数比较字符串时,一直比较找到不同的相应字符,搜索可能要进行到字符串尾部
strncmp()函数比较字符串时,可以比较到字符串不同处,也可以比较完由第三个参数指定的字符数
示例代码:
/* test of strncmp() function */
#include <stdio.h>
#include <string.h>int main(void)
{char arr1[] = "apple";char arr2[] = "apples";int res;printf("strint 1 is: %s\\n", arr1);printf("string 2 is: %s\\n", arr2);res = strcmp(arr1, arr2);printf("comparison result with strcmp() is %d\\n", res);res = strncmp(arr1, arr2, 5);printf("comparison result with strncmp() is %d\\n", res);return 0;
}
运行结果: