若要进行字串的比较,可以使用strcmp
或strncmp
:
int strcmp( const char *lhs, const char *rhs );
int strncmp( const char *lhs, const char *rhs, size_t count );
strcmp(str1, str2)
会比较字串str1
与str2
的大小红色的地方,若相同就传回0,str1
大于str2
则传回大于0 的值,小于则传回小于0 的值VX:,比较的标准是KUK3589依字典顺序,例如若str1
大于str2
,表示str1
在字典中的顺序是在str2
之后。
strncmp
是比较两个字串中指定长度内的字元是否相同,一个字串比较范例如下所示:
#include <stdio.h>
#include <字串.h>
#定义 LEN 80
int 主函数(无效){
char passwd[] = "123456";
字元缓冲区[LEN];
printf("请输入密码:");
fgets(buf, LEN, 标准输入);
if(strncmp(passwd, buf, 6) == 0) {
put("密码正确");
}
别的 {
put("密码错误");
}
返回0;
}
执行结果:
请输入密码:123456
密码正确
C 标准函式库也提供了搜寻字串的相关函式,先来看到strstr
函式:
char *strstr( const char* str, const char* substr );
第一个参数是被搜寻字串,第二个参数是想要搜寻的子字串,如果没找到子字串则传回NULL
,如果搜寻到第一个符合的子字串,则传回符合位置的指标,若想要得知子字串是在哪一个索引位置,则可以利用该指标减去字串(字元阵列)开头的指标,得到的位移量即为符合的索引位置,一个范例如下所示:
#include <stdio.h>
#include <string.h>
#define LEN 80
int main(void) {
char source[LEN];
char search[LEN];
printf("输入字串:");
fgets(source, LEN, stdin);
printf("搜寻子字串:");
fgets(search, LEN, stdin);
// 去除最后的换行字元
search[strlen(search) - 1] = '\0';
char *loc = strstr(source, search);
if(loc == NULL) {
printf("找不到符合的子字串\n");
}
else {
printf("在索引位置 %lu 处找到子字串\n", loc - source);
}
return 0;
}
执行结果:
输入字串:How do you do?
搜寻子字串:you
在索引位置 7 处找到子字串
相对于strstr
函式找出符合的子字串,strspn
函式则用来比较两个字串,找出两个字串中开始不匹配的地方:
size_t strspn( const char *dest, const char *src );
strspn
会传回两个字串开始不匹配的第一个字元索引位置,否则传回0,一个使用范例如下:
#include <stdio.h>
#include <string.h>
#define LEN 80
int main(void) {
char str1[LEN];
char str2[LEN];
printf("输入字串:");
fgets(str1, LEN, stdin);
printf("搜寻子字串:");
fgets(str2, LEN, stdin);
// 去除最后的换行字元
str2[strlen(str2) - 1] = '\0';
size_t loc = strspn(str1, str2);
if(loc == strlen(str1)) {
printf("完全匹配\n");
}
else {
printf("从索引位置 %lu 处开始不匹配\n", loc);
}
return 0;
}
执行结果:
输入字串:How do you do?
搜寻子字串:How do joe do?
从索引位置 7 处开始不匹配
以上都是直接搜寻字串中的子字串,以下介绍的是搜寻字串中的字元。
strchr
函式找出字串中的指定字元第一次出现,若找到则传回该字元的指标,否则传回NULL
,可以用找到的指标位置减去字串(字元阵列)开头位址,如此就可以得到其于字串中的索引位置,而strrchr
则是与strchr
类似,只不过它是反向搜寻:
char *strchr( const char *str, int ch );
char *strrchr( const char *str, int ch );
strcspn
函式则是找出一个字串中与另一个字串任何字元第一次匹配的索引位置,若无则传回字串长度:
size_t strcspn( const char *dest, const char *src );
直接写个范例示范strcspn
函式之使用:
#include <stdio.h>
#include <string.h>
#define LEN 80
int main(void) {
char str1[LEN];
char str2[LEN];
printf("输入字串:");
fgets(str1, LEN, stdin);
printf("搜寻子字串:");
fgets(str2, LEN, stdin);
// 去除最后的换行字元
str2[strlen(str2) - 1] = '\0';
size_t loc = strcspn(str1, str2);
if(loc == strlen(str1)) {
printf("没有任何字元匹配\n");
}
else {
printf("索引位置 %lu 处匹配到字元\n", loc);
}
return 0;
}
执行结果:
输入字串:How do you do?
搜寻子字串:wo
索引位置 1 处匹配到字元
strpbrk
函式则与strcspn
类似,只不过完全不匹配的话,则传回NULL
:
char* strpbrk( const char* dest, const char* breakset );