2016-11-22 27 views
0

我從我的教程中獲得了一個新任務,用於實現一些基本字符串操作,如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死schnHello世界怎麼樣?

我根本無法理解爲什麼輸出看起來像這樣。我在那裏有一個邏輯錯誤嗎?

+0

爲了您'length'和'copy'和'append'和'substr'功能,我建議你看看也許類似的標準庫函數'strlen'和'strcpy'和'strcat'和'strstr' *及其變體*來看看這些函數是如何聲明的。也許你可以找到一些開源的實現,看看別人怎麼做。 –

+0

'insert'的預期行爲是什麼,在您當前的輸入情況下期望的輸出是多少? –

+0

預期的產量將是:「HelloHalt die schnauze!怎麼回事?」 插入應插入任何字符串到另一個並將結果保存在緩衝區中。 – ExOfDe

回答

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; 
}