为了账号安全,请及时绑定邮箱和手机立即绑定

运行结果为"The substring is:national"?为什么

运行结果为"The substring is:national"?为什么

C PHP
猛跑小猪 2023-03-15 21:17:18
编写字符串处理函数_strstr(str1, str2),返回str1串中与str2相同的子串和其后续字符.下面的是执行结果正确的程序:字符串匹配函数char* _strstr(char* a,char* b)#include "stdio.h"//#include <string.h>int _strlen(char* a){int i;for(i=0;a[i];i++);return i;}int _strncmp(char* a,char* b,int n){int i=0,s;while(a[i]==b[i] && a[i])i++;if(i>=n)return 0;else if(i<n && a[i]-b[i])return 1;else return -1;}char* _strstr(char* a,char* b){int len2;if ( !(len2 = _strlen(b)) )return a;for ( ; *a; ++a ){if ( *a == *b && _strncmp( a, b, len2 )==0 )return a;}return NULL;} int main(void){char *str1 = "Borland International", *str2 = "nation", *ptr;//clrscr();ptr = _strstr(str1, str2);printf("The substring is: %s\n", ptr);return 0;}运行结果为"The substring is:national"其中的字符串比较函数_strncmp是用本人自己的算法写的,现在有个问题,就是当用msdn中关于strcmp函数的算法写一个本程序中的_strncmp函数时,为什么执行的结果会是(null)呢?代码如下:#include "stdio.h"//#include <string.h>int _strlen(char* a){int i;for(i=0;a[i];i++);return i;}int _strncmp(char* a,char* b,int n){int i=0,s;while(!(s=a[i]-b[i]) && a[i] && i<=n)i++;if(s<0)return -1;if(s>0)return 1;elsereturn 0;}char* _strstr(char* a,char* b){int len2;if ( !(len2 = _strlen(b)) )return a;for ( ; *a; ++a ){if ( *a == *b && _strncmp( a, b, len2 )==0 )return a;}return NULL;} int main(void){char *str1 = "Borland International", *str2 = "nation", *ptr;//clrscr();ptr = _strstr(str1, str2);printf("The substring is: %s\n", ptr);return 0;}
查看完整描述

2 回答

?
慕斯王

TA贡献1864条经验 获得超2个赞

仔细看看这两段代码就知道了:
关键,字符串后面都以 \0字符结束,而你的strlen函数是计算了\0字符的。
int _strncmp(char* a,char* b,int n)
{
int i=0,s;
while(a[i]==b[i] && a[i])
i++;
if(i>=n) //关键在这里,你的算法中,如果b比a短,也就是比较到了\0时,i=0,返回了0,即相等
return 0;
else if(i<n && a[i]-b[i])
return 1;
else 
return -1;
}

int _strncmp(char* a,char* b,int n)
{
int i=0,s;
while(!(s=a[i]-b[i]) && a[i] && i<=n) //他的算法中,你传递的n是包含\0字符的,因此当b比a短的时候,必然会比较到 s=a[n]-b[n] ,s <> 0 ,因此返回的必然是非0,即不等,所以。。。
i++;
if(s<0)
return -1;
if(s>0)
return 1;
else
return 0;
}

查看完整回答
反对 回复 2023-03-18
?
富国沪深

TA贡献1790条经验 获得超9个赞

void ltrim(char str[])
{
int count=0;//记录字符串左边有多少个空格
char *p=NULL;
p=str;
while(*p==' ' && *p!='\0')//循环检查左边空格的个数
{
count++;
p++;
}

p=str+count;
while(count>0 && *p!='\0')//循环,把后面的字符前移
{
*(p-count)=*p;
p++;
}
*(p-count)='\0';
}

void rtrim(char str[])
{
int count=0;//记录字符串右边有多少个空格
char *p=NULL;
p=str;

while(*p!='\0')//循环找到字符串结束
{
p++;
}

p--;
while(p>=str && *p==' ')//循环消灭后面的空格
{
*p='\0';
p--;
}
}

void trim(char str[]) //直接调用上面两个函数
{
ltrim(str);
rtrim(str);
}

void delchar(char str[],char ch) 
{
int count=0;
char *p1=NULL,*p2=NULL,*Y=NULL;
p1=str;
while(*p1!='\0')
{
p1++;
count++;
}
Y=(char *)malloc(count+1);//为了节约运算时间,申请一个缓冲内存
//malloc函数要求引入#include<stdlib.h>函数
p1=str;
p2=Y;
while(*p1!='\0')
{
if(*p1!=ch)
{
*p2=*p1;
p2++;
}
p1++;
}
*p2='\0';

p1=str;
p2=Y;
while(*p2!='\0')
{
*p1=*p2;
p1++;
p2++;
}
*p1='\0';
free(Y);//释放内存
}


查看完整回答
反对 回复 2023-03-18
  • 2 回答
  • 0 关注
  • 60 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信