zoukankan      html  css  js  c++  java
  • 不调用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]!='';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;
    }

     

  • 相关阅读:
    html 知识
    mysql use mysql hang
    微信机器人 简化版
    Tk::Table
    好友消息和群消息区别
    完整的微信登陆 接收消息流程
    Python OOP知识积累
    Python OOP知识积累
    JSTL EL 详解
    JSP中的EL表达式详细介绍
  • 原文地址:https://www.cnblogs.com/shamoguzhou/p/7862276.html
Copyright © 2011-2022 走看看