S1e22第三题求助
本帖最后由 Khayal 于 2022-10-30 21:04 编辑实现 strncmp 函数,允许用户指定前 n 个字符进行对比,这一次要求支持中英文混合的字符串比较噢!
我写的如下:
#include <stdio.h>
#define MAX 1024
int main()
{
char str1, str2;
char *target1 = str1, *target2 = str2;
int index = 1, n;
printf("Input the first string:");
fgets(str1, MAX, stdin);
printf("Input the secong string:");
fgets(str2, MAX, stdin);
printf("Input the number for comparing:");
scanf("%d", &n);
while (n && *target1 != '\0' && *target2 != '\0')
{
if (*target1++ != *target2++)
{
break;
}
index++;
n--;
}
if ((n == 0) || (*target1 == '\0' && *target2 == '\0'))
{
printf("The same!\n", index);
}
else
{
printf("Different in the %d char!\n", index);
}
return 0;
}
Q1:小甲鱼在while这里将中文的情况区分开来,即
char ch;
……
while (n && *target1 != '\0' && *target2 != '\0')
{
ch = *target1;
if (ch < 0)
{
if (*target1++ != *target2++ || *target1++ != *target2++)
{
break;
}
}
if (*target1++ != *target2++)
{
break;
}
index++;
n--;
}
但我看不用区分ch<0的情况也能成功?
Q2:如果我把n处写成这样:
while (n-- && *target1 != '\0' && *target2 != '\0')
而这个问题只会在最后一个字符不同时出现
求助大佬! #include <stdio.h>
#define MAX 1024
int strncmp(char * s1 , char * s2 , int n)
{
char * p1 , * p2 ;
int i , r ;
for(i = 0 , p1 = s1 , p2 = s2 ; * p1 && * p2 && i < n ; p1 ++ , p2 ++ , i ++) {
r = * p1 - * p2 ;
if(* p1 < 0) {
r = (* p1 - * p2) || (* (p1 + 1) - * (p2 + 1)) ;
p1 ++ ;
p2 ++ ;
}
if(r) break ;
}
return r ;
}
int main()
{
int n ;
char str1 , str2 ;
printf("Input the first string:") ;
fgets(str1, MAX, stdin) ;
printf("Input the secong string:") ;
fgets(str2, MAX, stdin) ;
printf("Input the number for comparing:") ;
scanf("%d", &n) ;
if(! strncmp(str1 , str2 , n)) printf("The same!\n") ;
else printf("the difference!\n") ;
}
页:
[1]