Cpp字符串处理记录

因为又懒又摸所以博客很久没更新了,今天就记录一下面向对象这门课的第一次上机实验课——CPP字符串处理

前情提要

在前天学了C++的引用,今天的任务就是改写前面夏季实训的字符串处理函数

实验过程

目标很简单,把原来的SWAP和STRCAT函数用C++的风格写一遍就好了

什么是引用呢?
简而言之,引用就是变量的一个别名,声明这个引用不会开辟内存空间,这个别名可以直接对变量本身进行操作

代码展示
首先是原来的C语言的SWAP。
这里需要用到二级指针,且调用时需要使用SWAP2_C(&str1,&str2)的方式

void SWAP2_C(char** a, char** b)
{
    char* t = *a;
    *a = *b;
    *b = t;
}

如果使用C++,那就可以用引用的方式直接对字符串进行操作:

void SWAP2_CPP(char*& a, char*& b)
{
    char* t = a;
    a = b;
    b = t;
}

怎么感觉就是在调用的时候先取地址呢?不过C中好像也做不到
之后就是STRCAT,和夏季实训中一样,中间需要" & "连接。
C部分没什么好讲的,直接抄夏季的就完事了。

char* STRCAT_C(char** dest, const char* source)
{
    const char* p = " & "; //中间插入部分
    char* t = *dest;
    char* temp = (char*)calloc(114514, sizeof(char));
    //既然是C就用C的方式去做
    int n = 0;
    for (; *t; t++, temp++)
    {
        *temp = *t;
        n++;
    }
    for (; *p; p++, temp++)
    {
        *temp = *p;
        n++;
    }
    for (; *source; source++, temp++)
    {
        *temp = *source;
        n++;
    }
    *dest = temp - n; //最后传值要回到数组头部
    return *dest;
}

C++部分同样可以使用引用

char* STRCAT_CPP(char*& dest, const char* source)
{
    const char* p = " & "; //中间插入部分
    char* t = dest;
    char* temp=new char[114514];
    int n = 0;
    for (; *t; t++, temp++)
    {
        *temp = *t;
        n++;
    }
    for (; *p; p++, temp++)
    {
        *temp = *p;
        n++;
    }
    for (; *source; source++, temp++)
    {
        *temp = *source;
        n++;
    }
    dest = temp - n; //最后传值要回到数组头部
    return dest;
}

值得注意的是,我们这里的temp就抛弃了C的malloc,而使用了C++的new来申请内存空间。
之后就是多文件编译运行,就成功了,好耶!o(*≧▽≦)ツ┏━┓
不过在这个过程中,因为改函数却没改头文件卡了我好久

posted @ 2020-09-09 14:48  DoRCL  阅读(167)  评论(0)    收藏  举报