不调用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;
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM