【发布时间】:2013-12-09 23:30:19
【问题描述】:
我想知道是否有人可以帮助我完成这个程序。 编写一个接收两个字符串的函数。该函数应将两个字符串与按字典顺序排在第一位的字符串结合起来。两个字符串之间应该有一个空格。在一行上打印结果字符串。在一行上打印结果字符串的长度。
#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会在组合单词时消除空格的影响,但是当我将不同的单词放入程序时,字符串长度总是以不同的数字关闭。任何帮助将不胜感激,谢谢。
【问题讨论】:
-
word1的长度不足。另外,不要添加strlen(word2),word1 包括word2。