c - 如何在 C 中解决此输出?

标签 c output

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

例如:

Input: excellent
Output: excellent,excellently

我不知道如何使输出像上面那样。

我的输出:

excellent,excellently,

它总是在最后给我一个逗号。

程序:描述 迭代地将字典中的每个单词转换为小写, 并将转换后的单词存储在lower中。 使用 strncmp 比较 input_str 和 lower 的前 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");
    }
}

最佳答案

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

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;
    }
}

关于c - 如何在 C 中解决此输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19786621/

相关文章:

Python:将大整数写入文件的最快方法

c - 如何引用二维数组?

c - 尝试从用户读取输入整数,不想接受 C 中的字符

c - %g 在 printf 中的工作原理

c - 理解指针

使用命令行参数的 C 管道

c++ - Ofstream 拒绝带参数的输入

c++ - 使用 g_object_ref() 重用小部件

java - 如何将一维数组分解为行?

c - 为什么 printf(创建单位矩阵)不打印输出?