2013-12-09 88 views
1

我想知道是否有人可以幫助我這個程序。 編寫一個需要兩個字符串的函數。函數應該將這兩個字符串與按字母順序排列的字符串結合起來。兩個琴絃之間應該有一個空格。將結果字符串打印在一行上。在一行上打印結果字符串的長度。比較,合併和確定字符串的長度?

#include <stdio.h> 
#include <string.h> 

int main(){ 

char word1[10]; 
char word2[10]; 
int length; 

//getting the words from input given by the user 
printf("Enter the first word. (10 Letters or less)\n"); 
scanf("%s", word1); 
printf("Enter the second word. (10 Letters or less)\n"); 
scanf("%s", word2); 

//comparing the two words entered 
if (strcmp(word1, word2)>0) 
    printf("%s comes before %s\n", word2, word1); 
else if (strcmp(word1, word2)<0) 
    printf("%s comes before %s\n", word1, word2); 
else 
    printf("Both words are the same!\n"); 

//combining the two words 
strcat(word1, " "); 
strcat(word1, word2); 
printf("\n%s\n", word1); 

//looking at the length of the two words 
length = strlen(word1) + strlen(word2) - 1; 
printf("The length of the words are %d.\n", length); 

return 0; 
} 

這是我上面的代碼。我決定打印出哪個詞首先用於我自己的可視化。我不確定如何組合這些詞彙,以便首先按字典順序排列的詞將是第一詞,以及如何確定兩者的結果長度。我認爲加上減號1會在合併單詞時消除空格的效果,但是當我將不同的單詞放入程序時,字符串的長度總是不同的數字。任何幫助將不勝感激,謝謝。

+0

沒有足夠的長度,以'word1'。另外,不添加'strlen(word2)',word1包含word2。 – BLUEPIXY

回答

0

留下內存分配與呼叫者A版:

/** Return 0 if not enough space, else length of resultant string. */ 
int stringOrder(const char * const str1, const char * const str2, char* retBuf, int bufLen) 
{ 
    const char* first = str1; 
    const char* second = str2; 
    int requiredLength = strlen(str1) + strlen(str2) + 2; 

    if (requiredLength > bufLen) 
     return 0; 

    if(strcmp(str1, str2) == 1) 
    { 
     first = str2; 
     second = str1; 
    } 

    strcpy(retBuf, first); 
    strcat(retBuf, " "); 
    strcat(retBuf, second); 

    return requiredLength - 1; 
} 

用法是這樣的:

#define LENGTH 128 
    const char* str1 = "world"; 
    const char* str2 = "hello"; 

    char result[128] = ""; 

    int ok = stringOrder(str1, str2, result, LENGTH); 

    if (ok) 
     printf("%s\n", result); 
    else 
     printf("Not enough space");