#include
#include
#include
char *mystrstr(char *string,char *findstring )
{
if (string == NULL || findstring == NULL)
{
return NULL;
}
int flag = 1;
while (*string != '\0')
{
char *p=string;
char *px = string;
char *now = findstring;
while (*now != '\0')
{
if (*px == *now)
{
px++;
now++;
}
else
{
flag = 0;
break;
}
}
if (flag == 1)
{
return p;
}
string++;
}
if (flag == 0)
{
return NULL;
}
}
void main()
{
char str1[20] = "i love you";
char str2[20] = "love";
char *p=mystrstr(str1, str2);
if (p == NULL)
{
printf("沒有找到\n");
}
else
{
printf("%c\n", *p);
}
system("pause");
}
改成了如下這樣:
#include <stdio.h>
#include <iostream>
using namespace std;
char *mystrstr(char *string,char *findstring )
{
if (string == NULL || findstring == NULL)
{
return NULL;
}
int flag = 1;
while (*string != '\0')
{
char *p=string;
char *px = string;
char *now = findstring;
while (*now != '\0')
{
if (*px == *now)
{
px++;
now++;
}
else
{
flag = 0;
break;
}
if(*now != '\0')
flag = 1;
}
if (flag == 1)
{
return p;
}
string++;
}
if (flag == 0)
{
return NULL;
}
}
void main()
{
char str1[20] = "i love you";
char str2[20] = "love";
char *p=mystrstr(str1, str2);
if (p == NULL)
{
printf("沒有找到\n");
}
else
{
printf("%c\n", *p);
}
system("pause");
}
就多加了一下兩句:
if(*now != '\0')
flag = 1;
while (*string != '\0')否則的話即使在某個位置兩個字符串都匹配上了,但是沒有把flag置1,無法跳出循環,
繼續進行while (*string != '\0')裡的循環,然後由於字符匹配不上,flag被置成0了