题目描述
设计函数 char *locatesubstr(char *str1,char *str2),查找str2指向的字符串在str1指向的字符串中首次出现的位置,返回指向该位置的指针。若str2指向的字符串不包含在str1指向的字符串中,则返回空指针NULL。
注意这里必须使用指针而不是数组下标来访问字符串。
输入与输出要求:输入两个长度不超过500的非空字符串str1和str2,字符串中可能出现空格,以换行符结束。输出str1中返回指针后的所有字符;否则输出“NULL!”。
程序运行效果:

Sample 1:
didjfsd dabcxxxxxx↙
abc↙
abcxxxxxx
Sample 2:
aaaaabcaaa↙
xxx↙
NULL!
PS:该方法没有用指针,和习题课的一道题很相似,稍微改一下就行

#include <stdio.h>
#include <string.h>
int main(void)
{
	int i,z=0,q,c=0,o=0;
	char ch[500],sh[500];
	gets(ch);
	gets(sh);
	int n=strlen(sh),m=strlen(ch);
	for(i=0;i<=m-n;i++)
	{
  			for(z=i,c=0;z<n+i;z++)
			{
				if(ch[z]==sh[z-i])
					c++;
				else
					break;
			}
			if(c/n==1)
			{
				for(z=i;z<m;z++)
				{
					printf(\"%c\",ch[z]);
				}
				o++;
				break;
			}
	}
	if(o==0)
		printf(\"NULL!\");
	return 0;
}

亲测可过

收藏 打印