zl程序教程

您现在的位置是:首页 >  其它

当前栏目

习题 8.17 写一函数,实现两个字符串的比较。即自己写一个strcmp函数,函数原型为int strcmp(char *p1, char *p2);

实现 函数 一个 字符串 自己 比较 两个 习题
2023-09-14 09:06:56 时间

C程序设计(第四版) 谭浩强 习题8.17 个人设计

习题 8.17 写一函数,实现两个字符串的比较。即自己写一个strcmp函数,函数原型为int strcmp(char *p1, char *p2); 设p1指向字符串s1,p2指向字符串s2。要求当s1=s2时,返回值为0;若s1!=s2,返回它们二者第1个不同字符的ASCII码差值(如"BOY"与"BAD",第2个字母不同,"O"与"A"之差为79-65=14)。如果s1>s2,则输出正值;如果s1<s2,则输出负值。

代码块:

方法1:

#include <stdio.h>
#include <stdlib.h>
int strcmp(char *p1, char *p2);                 //定义strcmp函数
int main()
{
	char s1[20], s2[20];
	printf("Please enter s1 string: ");        //输入字符串s1
	gets(s1);
	printf("Please enter s2 string: ");        //输入字符串s2
	gets(s2);
	printf("Result: %d\n", strcmp(s1, s2));    //输出返回值
	system("pause");
	return 0;
}
//strcmp函数
int strcmp(char *p1, char *p2)
{
	int r, t;
	for (; *p1==*p2&&(*p1!='\0'||*p2!='\0'); p1++, p2++);
	r=*p1-*p2;
	r==0 ? t=0 : t=*p1-*p2;
	return t;
}

方法2:(利用动态内存分配)

#include <stdio.h>
#include <stdlib.h>
void input(char *s1, char *s2);
int strcmp(char *p1, char *p2);
int main()
{
	char *str1, *str2;
	str1=(char *)malloc(30*sizeof(char));
	str2=(char *)malloc(30*sizeof(char));
	input(str1, str2);
	printf("Value=%d\n", strcmp(str1, str2));
	free(str1);
	free(str2);
	system("pause");
	return 0;
}
void input(char *s1, char *s2)
{
	printf("Please enter S1: ");
	gets(s1);
	printf("Please enter S2: ");
	gets(s2);
}
int strcmp(char *p1, char *p2)
{
	char *p, *q;
	int value;
	for (p=p1, q=p2; *p!='\0'||*q!='\0'; p++, q++)
		if (*p!=*q){
			value=*p-*q;
			break;
		}
	if (p==q) value=0;
	return value;
}