不調用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