急求一道C语言指针题的解答

2024-12-02 23:35:22
推荐回答(2个)
回答(1):

#include
#define N 50
char* substr(char* s,int startloc,int len){ //求子串
char* sub=new char[N];
char*p,*q;
int length=0; /高雀/记录原串长
p=q=s;
while(*p++!='\0'){
length++;
if(length==startloc)
q=p;
}
if(length-startloc+1 printf("要求的子串超出原串长度范围!\n");
return 0;
}
int i=0;
while(i sub[i]=s[i+startloc];
i++;
}
sub[i]='\0';
return sub;
}
void main(){
char s[N],*sub;
int startloc,len;
printf("缓丛输入原字符串:\n");
scanf("%s",&s);
printf("输入子串起始位置\n");
scanf("%d",&startloc);
printf("输入子串长度\n");
scanf("%d",&len);
sub=substr(s,startloc,len);
if(sub)
printf("扰念樱子串为:%s",sub);
}

回答(2):

VC环境下运行过的

#include
#include
char* substr(char* s,int startloc,int len)
{
char* s2;
int i;

s2=(char*)malloc(20*sizeof(char));
for(i=0;i<野顷len;i++)
s2[i]=s[i+startloc];
s2[i]='\0';
return(s2);
}
void main()
{
printf("%s\培罩n",substr("123456648"颂中陆,0,4));
}