比较,组合和确定弦的长度?

时间:2013-12-09 23:30:20

标签: c string

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

#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会在组合单词时取出空格的效果但是当我将不同的单词放入程序时,字符串长度总是被不同的数字关闭。任何帮助将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:0)

与调用者保留内存分配的版本:

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