zoukankan      html  css  js  c++  java
  • 自己实现的库函数1(strlen,strcpy,strcmp,strcat)

    为了便于理解和使用库函数,先把自己实现的几个函数以及测试函数呈现如下。

    //求字符串长度的函数
    int my_strlen(const char* pStr)
    {
    assert(pStr != NULL);
    int length = 0;
    while (*pStr++ != '')
    {
    length++;
    }
    return length;
    }
    //字符串拷贝函数
    char* my_strcpy(char* strDest, const char* strSrc)
    {
    assert(strDest != NULL && strSrc != NULL);
    char* pDest = strDest; //保护参数
    const char* pSrc = strSrc;
    while (*pSrc != '')
    {
    *pDest++ = *pSrc++;
    }
    *pDest = '';
    return strDest;
    }
    //字符串比较函数
    int my_strcmp(const char* strDest, const char* strSrc)
    {
    assert(strDest != NULL && strSrc != NULL);
    if (*strDest == ''&&*strSrc != '')
    {
    return 0;
    }
    const char* pDest = strDest;
    const char* pSrc = strSrc;
    int result = 0; //用于记录比较结果
    while (*pDest != '' || *pSrc != '')
    {
    if ((result = *pDest - *pSrc) != 0)
    {
    break; //当两字符串不相等时跳出,相等是继续往后指
    }
    pDest++;
    pSrc++;
    }
    if (result > 0)
    {
    result = 1;
    }
    else if (result<0)
    {
    result = -1;
    }
    return result;
    }
    //字符串连接函数
    char* my_strcat(char* strDest, char* strSrc)
    {
    assert(strDest != NULL && strSrc != NULL);
    char* pDest = strDest;
    char* pSrc = strSrc;
    while(*pDest != '') //先将pDest指到字符串末尾
    {
    pDest++;
    }
    while (*pSrc != '')
    {
    *pDest++ = *pSrc++;
    }
    *pDest = '';
    return strDest;
    }
    void Test()
    {
    char c1[5] = "abcd";
    char c2[4] = "123";
    char c3[20] = "123456";
    	printf("c1-length:%d
    ", my_strlen(c1));
    printf("my_strcpy(c1,c2):%s ", my_strcpy(c1, c2));
    //printf("%s ", my_strcpy(c1, c3)); //不能处理这种超出范围的,程序会崩溃!!
    printf("my_strcmp(c1,c2):%d ", my_strcmp(c1, c2));
    printf("my_strcmp(c2,c3):%d ", my_strcmp(c2, c3));
    printf("my_strcat(c3,c2):%s ",my_strcat(c3,c2));
    }
  • 相关阅读:
    LeetCode 1110. Delete Nodes And Return Forest
    LeetCode 473. Matchsticks to Square
    LeetCode 886. Possible Bipartition
    LeetCode 737. Sentence Similarity II
    LeetCode 734. Sentence Similarity
    LeetCode 491. Increasing Subsequences
    LeetCode 1020. Number of Enclaves
    LeetCode 531. Lonely Pixel I
    LeetCode 1091. Shortest Path in Binary Matrix
    LeetCode 590. N-ary Tree Postorder Traversal
  • 原文地址:https://www.cnblogs.com/guochuanrui/p/5367553.html
Copyright © 2011-2022 走看看