【问题标题】:Comparing, combining and determining the length of the strings?比较、组合和确定字符串的长度?
【发布时间】: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。

标签: c string


【解决方案1】:

将内存分配留给调用者的版本:

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

【讨论】:

    猜你喜欢
    • 2013-02-12
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 2014-12-08
    • 2020-02-04
    • 2016-02-04
    相关资源
    最近更新 更多