【问题标题】:How to solve this output in C?如何在 C 中解决此输出?
【发布时间】:2013-11-16 04:29:35
【问题描述】:

每次找到子字符串时,我都必须在字符串中搜索子字符串并显示下面给出的完整单词-

例如:

Input: excellent
Output: excellent,excellently

我不知道如何制作像上面那样的输出。

我的输出:

excellent,excellently,

最后总是给我一个逗号。

程序:描述 迭代地将字典中的每个单词转换为小写, 并将转换后的单词存储在较低的位置。 使用 strncmp 比较 input_str 的前 len 个字符和更低的字符。 如果strncmp的返回值为0,那么前len个字符 两个字符串中的相同。

void complete(char *input_str)
{
    int len = strlen(input_str);
    int i, j, found;
    char lower[30];
    found = 0;

    for(i=0;i<n_words;i++)
    {
        for(j=0;j<strlen(dictionary[i]);j++)
        {
          lower[j] = tolower(dictionary[i][j]);

        }
        lower[j+1]='\0';
        found=strncmp(input_str,lower,len);

        if(found==0)//found the string n print out
        {
           printf("%s",dictionary[i]);
           printf(",");
        }
    }

    if (!found) {
        printf("None.\n");
    } else {
        printf("\n");
    }
}

【问题讨论】:

    标签: c output


    【解决方案1】:

    在打印第二个单词之前检查您是否已经打印了一个单词:

    char printed = 0;
    for (i=0; i < n_words; i++)
    {
        for(j = 0; j < strlen(dictionary[i]); j++)
          lower[j] = tolower(dictionary[i][j]);
        lower[j + 1] = '\0';
        found = strncmp(input_str, lower, len);
    
        if (found == 0)//found the string n print out
        {
           if (printed)
             printf(",");
           printf("%s", dictionary[i]);
           printed = 1;
        }
    }
    

    【讨论】:

      【解决方案2】:

      对于逗号打印问题,我倾向于使用两种方法:

      1. 在循环开始时,打印逗号 if i &gt; 0
      2. 最后(打印真实值后),打印逗号 if i &lt; (n - 1)

      您可以使用其中任何一个,第一个更简单,因为比较更简单,但它可能稍微不太方便,因为它会及时移动逗号打印 (!)。在每次循环迭代中,您都在打印属于上一次迭代的逗号。至少我的感觉是这样,但当然这是相当主观的。

      【讨论】:

        猜你喜欢
        • 2021-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-07
        • 1970-01-01
        • 2020-11-02
        • 2014-05-11
        相关资源
        最近更新 更多