面试基础_03实现strcpy、strcat、strcmp、strlen


实现代码例如以下:

/************************************************************************* 
    > File Name: testString.h
    > Author: qiaozp 
    > Mail: qiaozongpeng@163.com 
    > Created Time: 2014-9-30 11:21:15
 ************************************************************************/ 
#include <iostream>
#include <string.h>
using namespace std;

//实现字符串拷贝
char* _strcpy(char* src, char* dst)
{
    if (src == NULL)
    {
        return NULL;
    }
    char* tmp = src;
    int i = 0;
    while (*tmp)
    {
        dst[i++] = *(tmp++);
    }
    dst[i] = '';
    return dst;
}

//实现字符串追加
char* _strcat(char* dst, char* src)
{
    if (src == NULL)
    {
        return NULL;
    }

    char* tmp = src;
    int pos = strlen(dst);
    while (*tmp)
    {
        dst[pos++] = *(tmp++);
    }
    dst[pos] = '';

    return dst;
}

//实现获取字符串长度
int _strlen(char* sz)
{
    char* tmp = sz;
    int i = 0;
    while (*tmp)
    {
        ++i;
        ++tmp;
    }
    return i;
}

//实现字符串比較
int _strcmp(char* srcA, char* srcB)
{
    char* cmpA = srcA;
    char* cmpB = srcB;
    //1 按位比較大小
    while ((*cmpA) && (*cmpB))
    {
        if (*cmpA = *cmpB)
        {
            ++cmpA;
            ++cmpB;
            continue;
        }
        else if (*cmpA > *cmpB)
        {
            return 1;
        }
        else
        {
            return -1;
        }
    }
    
    //2 比較长度
    return _strlen(srcA) - _strlen(srcB);
}

int main()
{
    char* p = "you are a student.";
    char e[30] = {0};
    if (_strcpy(p, e) == NULL)
    {
        return -1;
    }
    cout << "拷贝后的字符串:" << e << endl;


    if (_strcat(e, "name : qiao") == NULL)
    {
        return -1;
    }
    cout << "追加后的字符串:" << e << endl;

    cout << _strlen(p) << endl;

    cout << _strcmp("qiao", "qiap") << endl;
}


原文地址:https://www.cnblogs.com/liguangsunls/p/6943561.html