每天一道C++笔试题 III --- strcmp

来源:互联网 发布:天津seo源诊断 编辑:程序博客网 时间:2024/05/29 18:55

这道题主要考察指针和字符串(char[]),这是C语言必备的技能,但指针在C++也是重要之极。

题目是大家都熟悉的老调重弹,帮助大家温习之。

不使用库函数,编写函数int strcmp(char *source, char *dest) 相等返回0,不等返回-1。

背景知识:

char string[] = "luck";

1、字符数组的最后添加一个结束字符'\0'就是字符串。

2、用printf("%s",string)即可打印此字符串。

3、数组名string表示数组的首地址。与指针的关系如下代码:

#include <stdio.h>int main(){char string[] = "luck";char * pString = string;printf("string:%s",pString);return 0;}

解题思路:

最简单:做一个循环,对比两个字符串的元素是否相同,不同则返回-1;循环结束后没有找到不同,返回0.

int strcmp(char *source,char *dest){while(*source != '\0'){if((*source - *dest) != 0){printf("return %d \n",*source - *dest);return -1;}else{printf("point ++ \n");source++;dest++;}}return 0;}

逻辑清晰后,上面两个判断条件可以更加精简一些,下面是全部测试代码:

#include <stdio.h>int strcmp(char *source,char *dest){while(*source){if(*source - *dest){printf("return %d \n",*source - *dest);return -1;}else{printf("point ++ \n");source++;dest++;}}return 0;}int main(){int returnValue;char str1[80],str2[80];printf("please input a string:");scanf("%s",str1);printf("please input another string:");scanf("%s",str2);returnValue = strcmp(str1,str2);if(returnValue == 0){printf("Same string!");}else{printf("Different string!");}return 0;}


原创粉丝点击