单片机中接收到奥串口的指令一般为字符串,如果使用strncmp比较是否为我们的指令集中的指令,则不能区分大小写,这里可以使用strcasecmp( )函数和strncasecmp( )函数,来对接收到的字符串指令进行接收比较,并且可以不区分大小写,包含头文件include“stdio.h”
下面对strcasecmp( )函数和strncasecmp( )函数的原型以及应用进行介绍:
strcasecmp( )函数说明:
strcasecmp()用来比较参数s1和s2字符串,比较时会自动忽略大小写的差异。
返回值 若参数s1和s2字符串相同则返回0。s1长度大于s2长度则返回大于0 的值,s1 长度若小于s2 长度则返回小于0的值.
#include ”stdio.h“
#include “string.h”
#include ”ctype.h“
int strcasecmp(const char *s1, const char *s2)
{
int c1, c2;
do {
c1 = tolower(*s1++);
c2 = tolower(*s2++);
} while(c1 == c2 && c1 != 0);
return c1 - c2;
}
int main(void)
{
int n = 4;
char str1[] = "Acef";
char str2[] = "ACEFd";
printf("strcasecmp(str1, str2) = %d/n", strcasecmp(str1, str2));
return 0;
}
strncasecmp()函数说明:
strncasecmp()用来比较参数s1和s2字符串前n个字符,比较时会自动忽略大小写的差异
返回值 :若参数s1和s2字符串相同则返回0 s1若大于s2则返回大于0的值 s1若小于s2则返回小于0的值
#include ”stdio.h“
#include “string.h”
#include ”ctype.h
int mystrncasecmp(const char *s1, const char *s2, int n)
{
int c1, c2;
do {
c1 = tolower(*s1++);
c2 = tolower(*s2++);
} while((--n > 0) && c1 == c2 && c1 != 0);
return c1 - c2;
}
int main(void)
{
int n = 4;
char str3[] = "ABCf";
char str4[] = "abcd";
printf("mystrncasecmp(str3, str4, n) = %d/n", mystrncasecmp(str3, str4, n));
return 0;
}
『本文转载自网络,版权归原作者所有,如有侵权请联系删除』