2013-12-09 52 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");