strstr:
int strstr(const char *string,const char *substring)
{
if (string == NULL || substring == NULL)
return -1;
int lenstr=0;
int lensub=0;
for(int i=0;string[i]!=' ';i++)
{
lenstr++;
}
for(int i=0;substring[i]!=' ';i++)
{
lensub++;
}
if (lenstr < lensub)
return -1;
int len = lenstr - lensub;
for (int i = 0; i <= len; i++)
//复杂度为O(m*n)
{
for (int j = 0; j < lensub; j++)
{
if (string[i+j] != substring[j])
break;
}
if (j == lensub)
return i + 1;
}
return -1;
}
返回的是第一个子字符串出现的位置
strcpy:
#include<iostream>
#include<stdio.h>
using namespace std;
char *strcpy(char *strDest, const char *strSrc)
{
if ((strDest == NULL) || (strSrc == NULL))
{
return NULL;
}
char *address = strDest;
while ((*strDest++ = *strSrc++) != ' ');
return address;
}
int main()
{
char *strSrc = "abc";
char *strDest = new char[20];
cout << strSrc << endl;
strDest = strcpy(strDest, strSrc);
cout << strDest << endl;
return 0;
}