c - Print the longest word of a string -


i wrote following code

#include<stdio.h>  int main(void) {     int i, max = 0, count = 0, j;     char str[] = "i'm programmer";      for(i = 0; < str[i]; i++)     {         if (str[i] != ' ')             count++;         else         {             if (max < count)             {                 j = - count;                 max = count;             }             count = 0;         }     }     for(i = j; < j + max; i++)         printf("%c", str[i]);      return 0; } 

with intention find , print longest word, not work when longest word in last i'm programmer printed i'm instead of programmer

how solve problem, gives me hand

the terminating condition of for loop wrong. should be:

    for(i = 0; < strlen(str) + 1; i++) 

and also, since @ end of string don't have ' ', have '\0', should change:

    if (str[i] != ' ') 

to:

    if (str[i] != ' ' && str[i] != '\0') 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -