字符串函数:insert - 通过复制函数自我实现

时间:2016-11-22 19:50:39

标签: c string insert

我从我的教学中得到了一个新任务来实现一些基本的字符串操作,如append,remove,substr和insert。

当我在思考如何处理这个问题时,我想我可以写一个复制功能... ...

int copy(char* buffer,char * string,int begin,int end)
{
    if(end == 0)
        end = length(string);

    //Copy from begin to end and save result into buffer
    for(int i = 0; i < end;i++)
        buffer[i] = *(string+begin+i);

    return end;
}

有了这个实现,所以我的想法我可以实现我老师问的所有其他功能:

void insert(char* buffer,char * string, char * toInsert, int begin,int end)
{
    //Copy till the position of the original string
     begin = copy(buffer,
                  string,0,begin);

    //Insert
    //copy from the last change of the original string
     begin = copy(buffer+begin,
                  toInsert,0,end);

    //Copy whats left
    copy(buffer+begin,
         string);

}

因此,如果我现在尝试使用此函数插入​​一些东西,我会得到一些奇怪的输出:

int main() {

char * Hallo       = "Hello World how are things?";
char * appendix    = "Halt die schnauze!";

char buffer[128];
for (int i = 0; i < 128;i++)
    buffer[i] = -0;



insert(buffer,Hallo,appendix,5,0);
printf("%s\n",buffer);

return 0;
}

输出: HelloHalt die schnHello World世界怎么样?

我根本无法理解为什么输出看起来像这样。那里有逻辑错误吗?

1 个答案:

答案 0 :(得分:1)

像这样解决:

#include <stdio.h>

size_t length(const char *s){
    size_t len = 0;
    while(*s++){
        ++len;
    }
    return len;
}

int copy(char *buffer, const char *string, int begin, int end){
    int len = 0;//copy length

    if(end == 0)
        end = length(string);

    for(int i = begin; i < end; i++)//End position is not included
        buffer[len++] = string[i];

    return len;
}

void insert(char *buffer, const char *string, const char *toInsert, int begin, int end){
    int len;
    len  = copy(buffer, string, 0, begin);
    len += copy(buffer + len, toInsert, 0, end);
    len += copy(buffer + len, string, begin, end);
    buffer[len] = 0;
}

int main(void) {
    char * Hallo = "Hello World how are things?";
    char * appendix = "Halt die schnauze!";
    char buffer[128] = {0};

    insert(buffer, Hallo, appendix, 5, 0);
    printf("%s\n",buffer);

    return 0;
}