C 比较、组合和确定字符串的长度?

C 比较、组合和确定字符串的长度?,c,string,C,String,我想知道是否有人能帮我做这个项目。 编写一个包含两个字符串的函数。函数应该将这两个字符串与按字典顺序排列的第一个字符串组合在一起。两个字符串之间应该有一个空格。在一行上打印结果字符串。在一行上打印结果字符串的长度 #include <stdio.h> #include <string.h> int main (){ char word1[10]; char word2[10]; int length; //getting the words from input g

我想知道是否有人能帮我做这个项目。 编写一个包含两个字符串的函数。函数应该将这两个字符串与按字典顺序排列的第一个字符串组合在一起。两个字符串之间应该有一个空格。在一行上打印结果字符串。在一行上打印结果字符串的长度

#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;
}
#包括
#包括
int main(){
char-word1[10];
char-word2[10];
整数长度;
//从用户提供的输入中获取单词
printf(“输入第一个单词(10个字母或更少)\n”);
scanf(“%s”,单词1);
printf(“输入第二个单词(10个字母或更少)\n”);
scanf(“%s”,word2);
//比较输入的两个单词
如果(strcmp(字1,字2)>0)
printf(“%s位于%s\n”之前,单词2,单词1);

else if(strcmp(word1,word2)将内存分配留给调用者的版本:

/** 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");

没有足够的长度来
word1
。另外,没有添加
strlen(word2)
,word1包含word2。