|
发表于 2019-11-9 13:26:31
|
显示全部楼层
本帖最后由 jackz007 于 2019-11-9 13:36 编辑
这个代码逻辑存在问题,
- while (*target1 != '\0' && *target2 != '\0')
- {
- if (*target1++ != *target2++)
- {
- break;
- . . . . . .
- if (*target1 == '\0' && *target2 == '\0') printf("两个字符串完全一致!\n");
- else printf("两个字符串不完全相同,第 %d 个字符出现不同!\n", index) ;
复制代码
如果两个字符串长度相同,但是,最后一个字符不同也将被判定为 "两个字符串完全一致",原因出在指针字符比较,不论字符是否相同,两个指针都会增加,到字符串最后一个字符的时候,都会指向字符串结束标志 '\0',所以,会出现这个问题。
楼主的代码太过复杂,其实,是可以简单些的:
- #include <stdio.h>
- #include <string.h>
- #define MAX 1024
- int main()
- {
- char str1[MAX] , str2[MAX] , * target1 = str1 , * target2 = str2 ;
- int index ;
- bool f ;
- printf("请输入第一个字符串:") ;
- fgets(str1 , MAX , stdin) ;
- str1[strlen(str1) - 1] = '\0' ;
- if (strlen(str1) > 0) {
- printf("请输入第二个字符串:") ;
- fgets(str2 , MAX , stdin) ;
- str2[strlen(str2) - 1] = '\0' ;
- if (strlen(str2) > 0) {
- if (strlen(str1) == strlen(str2)) {
- for(f = true , index = 0 ; f ; index ++) if(* target1 ++ != * target2 ++) f = false ;
- if(f) printf("两个字符串完全一致!\n") ;
- else printf("两个字符串不完全相同,第 %d 个字符出现不同!\n", index) ;
- } else {
- printf("两个字符串长度不一致!\n") ;
- }
- }
- }
- return 0 ;
- }
复制代码
|
|