首页 > 试题广场 >

设计函数indexof(a,b),判断字符串a中是否包含字符

[问答题]
设计函数indexof(a,b)判断字符串a中是否包含字符串b,如果包含返回其位置,不包含返回-1。
int indexof(const char *s1, const char *s2)
{
	int length1, length2;
	const char *tmp = s1;

	length2 = strlen(s2);
	if (!length2)
	{
		/* code */
		printf("The s2 is NULL!.\n");
		exit(1);
	}

	length1 = strlen(tmp);
	while(length2 <= length1)
	{
		length1--;
		if (!memcmp(tmp, s2, length2))
		{
			/* code */
			return  (tmp - s1);
		}
		tmp++;
	}

        return -1;
}

编辑于 2015-09-02 18:42:04 回复(0)
#include<isotream>

using namespace std;
int indexof(char *p,char *q)
{
char pt=p,q1=q;
for(char *p1=p ;*p1!='\0';p1++)
{
for(char *temp=q;*temp!='\0';temp++)
{
if(*p1!=*temp)
break;
}
}
if(*temp=='\0')
return 1;
else
return -1;
}

int main()
{
char *p,*q;
cin>>p;
cin>>q;
cout<<indexof(p,q)<<endl;
return 0;
}
发表于 2015-08-31 22:28:29 回复(0)