不调用C/C++的字符串库函数,实现strstr(),strcpy()

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]!='\0';i++)
{
lenstr++;
}
for(int i=0;substring[i]!='\0';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++) != '\0');
return address;
}
int main()
{
char *strSrc = "abc";
char *strDest = new char[20];
cout << strSrc << endl;

strDest = strcpy(strDest, strSrc);

cout << strDest << endl;
return 0;
}

 

posted @ 2017-11-19 21:42  狼太白  阅读(1900)  评论(0编辑  收藏  举报