user2955810
user2955810

Reputation: 73

How to solve this output in C?

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

Upvotes: 7

Views: 173

Answers (2)

Eregrith
Eregrith

Reputation: 4366

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

Upvotes: 2

unwind
unwind

Reputation: 399959

There are two approaches that I tend to use for the comma-printing problem:

  1. At the start of the loop, print the comma if i > 0.
  2. At the end (after printing the real value), print the comma if i < (n - 1).

You can use either, the first is simpler since the comparison is simpler, but it can be slightly less convenient since it moves the comma-printing in time (!). On each loop iteration, you're printing the comma that belongs to the previous iteration. At least that how it's feels to me, but of course it's rather subjective.

Upvotes: 0

Related Questions