Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve this output in C?

Tags:

c

output

I have to search a substring in a string & display the complete word as given below everytime the substring is found-

eg:

Input: excellent
Output: excellent,excellently

I cannot figure out how to make the output like the one above.

My output:

excellent,excellently,

It always give me a comma in the end.

Prog: desc Iteratively convert every words in the dictionary into lowercase, and store the converted word in lower. Use strncmp to compare the first len characters of input_str and lower. If the return value of strncmp is 0, then the first len characters of the two strings are the same.

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");
    }
}
like image 928
user2955810 Avatar asked Nov 05 '13 10:11

user2955810


1 Answers

Check if you have already printed a word before printing a second one:

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;
    }
}
like image 195
Eregrith Avatar answered Oct 15 '22 22:10

Eregrith