2013-05-16 58 views
1

我已經看到了使用「strcopy」和「strcat」執行此操作的方法,但我不允許使用任何預定義的字符串函數。與2個字符串的連接

我給出:

void str_cat_101(char const input1[], char const input2[], char result[]); 

而且我必須把人物從輸入1和輸入2到結果(從左至右)。我需要使用兩個for循環,變量i和j代表我的參數列表中的兩個不同的字符串嗎?我知道如何從一個字符串中複製值,但我很困惑我將如何從兩個字符串中傳輸值。謝謝您的幫助。

所以這裏是我在我的string.c文件,但我覺得我沒有以正確的方式做。

void str_cat_101(char const input1[], char const input2[], char result[]) 
{ 
    int i, j; 
    for (i = 0; input1[i] != '\0'; i++) 
    { 
     result[i] = input1[i]; 
    } 
    result[i] = '\0'; 
    for (j = 0; input2[j] != '\0'; j++) 
    { 
     result[j] = input2[j]; 
    } 
    result[j] = '\0'; 
} 

這裏是我的測試案例:

void str_cat_101_tests(void) 
{ 
    char input1[4] = {'k', 'a', 'r', '\0'}; 
    char input2[3] = {'e', 'n', '\0'}; 
    char result[7]; 

    str_cat_101(input1, input2, result); 
    checkit_string("karen", result); 
} 

int main() 
{ 
    str_cat_101_tests(); 

    return 0; 
} 
+0

只是做兩次相同的事情。開始複製第二個複製第一個複製的位置。 – Barmar

+1

顯示你的嘗試,我們不會爲你做你的功課。 – Barmar

+0

哎呀,對不起!我應該包括我所做的。對不起,如果它似乎我想讓你們做我的功課。我非常感謝每個人發佈有關如何解決問題的提示和想法,我絕不會使用這個網站來爲我寫作業。我只是一個非常混亂的學生,他對編程完全陌生。 :)我一定會編輯我的問題,包括我迄今爲止所做的工作,感謝您的幫助! – Karen

回答

0
void str_cat_101(char const input1[], char const input2[], char result[]) 
{ 
    int i, j; 
    for (i = 0; input1[i] != '\0'; i++) 
    { 
     result[i] = input1[i]; 
    } 
// result[i] = '\0'; 
    for (j = 0; input2[j] != '\0'; j++) 
    { 
     result[i+j] = input2[j];//Copy to the location of the continued 
    } 
    result[i+j] = '\0'; 
} 
0

你可以不喜歡它(讀評論):

void str_cat_101(char const input1[], char const input2[], char result[]){ 
    int i=0, j=0; 
    while(input1[j]) // copy input1 
    result[i++] = input1[j++]; 
    --i; 
    j=0; 
    while(input2[j]) // append intput2 
    result[i++] = input2[j++];   
    result[i]='\0'; 
} 

result[]應足夠大,是strlen(input1) + strlen(input2) + 1

編輯

只是糾正你的第二個循環,你要追加到result[]從零位置的結果,而不是重新複製:

for (j = 0; input2[j] != '\0'; j++, i++) // notice i++ 
    { 
     result[i] = input2[j]; // notice `i` in index with result 
    } 
    result[i] = '\0'; // notice `i` 
+0

「我不允許使用任何預定義的字符串函數」的哪部分內容您不明白? – Barmar

+0

對不起,但是我不能使用任何預定義的字符串函數,所以我不認爲我可以使用strcpy或strcat。:(謝謝雖然。 – Karen

+0

所以我改變了我的第二個循環,就像你上面說的那樣,但是測試仍然沒有通過。 :(我會把我的測試案例上面。 – Karen

0

如果你可以使用鏈表來代替陣列輸入字符串,你必須做的是將字符串1的最後一個字符的指針設置爲字符串2的頭部,然後完成。如果鏈接列表不是一個選項,那麼您可以使用額外空間通過使用一個循環遍歷它們來存儲這兩個字符串。