strcmp(字符串比较)
原型:
头文件:#include< string.h>。
参数:两个字符串。
函数返回值:int。
解释: 返回值==0,说明两个字符串相等;
返回值<0,说明字符串1小于字符串2;
返回值>0,说明字符串1大于字符串2。
函数作用:比较字符串1和字符串2是否相等。
参考代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char a[] = "abc";
char b[] = "abc";
int ret = 0;
ret = strcmp(a, b);
if (ret == 0)
{
printf("字符串a与字符串b相等!\n");
}
else if (ret > 0)
{
printf("字符串a大于字符串b!\n");
}
else if (ret < 0)
{
printf("字符串a小于字符串b!\n");
}
system("pause");
return 0;
}
运行:
模拟实现:
//判断两个字符串是否相等
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
int my_strcmp(const char *dest, const char *src)
{
assert(dest); //断言,若指针为空,不执行后面的程序
assert(src); //断言,若指针为空,不执行后面的程序
while (*dest == *src) //若字符相等,则指针++
{
if (*src == '\0') //如果遇到\0,则两个字符串相等
return 0;
src++;
dest++;
}
if (*dest > *src)
{
return 1;
}
else if (*dest < *src)
return -1;
}
int main()
{
char a[] = "abcf";
char b[] = "abce";
int ret = 0;
ret = my_strcmp(a, b);
if (ret == 0)
{
printf("字符串a与字符串b相等!\n");
}
else if (ret > 0)
{
printf("字符串a大于字符串b!\n");
}
else if (ret < 0)
{
printf("字符串a小于字符串b!\n");
}
system("pause");
return 0;
}
运行:
strncmp(前n个字符串比较)
原型:
头文件:#include
//strncmp 比较前num个字符是否相等
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char arr[] = "abcdeeAFTT";
char brr[] = "abcdeREEEEEE";
int ret = 0;
int num = 0;
printf("请输入你要比较的字符个数:");
scanf("%d", &num);
ret = strncmp(arr, brr, num); //接收返回值
if (ret == 0)
{
printf("字符串arr前%d个字符与字符串brr前%d个字符相等!\n",num,num);
}
else if (ret > 0)
{
printf("字符串arr前%d个字符比字符串brr前%d个字符大!\n",num,num);
}
else if (ret < 0)
{
printf("字符串arr前%d个字符比字符串brr前%d个字符小!\n", num, num);
}
system("pause");
return 0;
}
运行:
模拟实现:
//strncmp 比较前num个字符是否相等
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
int my_strncmp(const char*dest, const char*src, size_t num)
{
assert(dest); //断言,若指针为空,不执行后面的程序
assert(src); //断言,若指针为空,不执行后面的程序
int count = 0; //计数
int k = num;
while (num--) //循环num次
{
if (*dest == *src) //如果字符相等,计数+1,指针右移
{
dest++;
src++;
count++;
if (count == k) //如果计数==要比较的字符个数,即前n个字符相等返回0
{
return 0;
}
if (*src == '\0') //或者如果两个字符串都遇到\0,返回0,减少循环次数。
{
return 0;
}
}
else if (*dest > *src)
return 1;
else
return -1;
}
}
int main()
{
char arr[] = "abcdeeAFTT";
char brr[] = "abcdeREEEEEE";
int ret = 0;
int num = 0;
printf("请输入你要比较的字符个数:");
scanf("%d", &num);
ret = my_strncmp(arr, brr, num); //接收返回值
if (ret == 0)
{
printf("字符串arr前%d个字符与字符串brr前%d个字符相等!\n",num,num);
}
else if (ret > 0)
{
printf("字符串arr前%d个字符比字符串brr前%d个字符大!\n",num,num);
}
else if (ret < 0)
{
printf("字符串arr前%d个字符比字符串brr前%d个字符小!\n", num, num);
}
system("pause");
return 0;
}
运行: