C语言-写一函数,实现两个字符串的比较。即自己写一个strcmp函数,函数原型为 int strcmp(char *pl,char *p2);

题目要求:

17.写一函数,实现两个字符串的比较。即自己写一个strcmp函数,函数原型为

int strcmp(char *pl,char *p2);

设p1指向字符串s1,p2指向字符串s2。要求当s1=s2时,返回值为0;若s1≠s2,返回它们二者第1个不同字符的 ASCI1码差值(如"BOY"与"BAD",第2个字母不同,0与A之差为79-65=14)。如果s1>s2,则输出正值;如果s1<s2,则输出负值。

具体程序:

c 复制代码
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
int main()
{
	int strcmp(char* p1, char* p2);
	char p1[100];
	char p2[100];
	printf("请输入两个字符串:\n");
	gets(p1);
	gets(p2);
	int result=strcmp(p1, p2);
	if (result == 0)
	{
		printf("字符串相同");
	}
	else
	{
		printf("%d", result);
	}
	return 0;
}
int strcmp(char* p1, char* p2)
{
	int i, j,flag = 1;
	for (i = 0; i < strlen(p1); i++)
	{
		if (*(p1 + i) - *(p2 + i) == 0)continue;
		else
		{
			flag = 0;
			return(*(p1 + i) - *(p2 + i));
		}
	}
	if (flag == 1)return 0;
}

运行结果:


相关推荐
p***h6432 小时前
JavaScript在Node.js中的异步编程
开发语言·javascript·node.js
薛慕昭2 小时前
嵌入式 C 语言猜大小游戏设计与实现
c语言·游戏
散峰而望2 小时前
C++数组(二)(算法竞赛)
开发语言·c++·算法·github
Porunarufu2 小时前
Java·关于List
java·开发语言
子不语1803 小时前
Python——函数
开发语言·python
ndjnddjxn3 小时前
Rust学习
开发语言·学习·rust
月光技术杂谈3 小时前
实战:C驱动框架嵌入Rust模块的互操作机制与完整流程
c语言·开发语言·rust·ffi·跨语言·bindgen·互操作
t198751283 小时前
基于MATLAB的指纹识别系统完整实现
开发语言·matlab
笑非不退3 小时前
C# c++ 实现程序开机自启动
开发语言·c++·c#
专注于大数据技术栈3 小时前
java学习--final
java·开发语言·学习