c - Reverse the words in a String -


this question has answer here:

i need program reverse words in string.

input: car fast
output: fast car my

int printrword(char * line) {     for(; *line; line++) {         if(*line == ' ') {             printrword(line + 1);              printf("%s", line);              return 0; // after find space set null          }     } }  int main(void) {     char *line = "this long line working with\n";     printf("%s", line);     printrword(line);       return 0; } 

i know need set space null after find it, , i've tried printrword(line + 1) = '\0'; , doesn't work suggestions?

find modified working code:

int printrword(char * line)

{

   char tempbuf[100]; //here length have hardcoded 100     char *ptr;    strcpy(tempbuf,line); //copied tempbuf keep original string unmodified     //replace \n null character     ptr = strrchr(tempbuf,'\n');     if(ptr != null)     {       *ptr = '\0';      }      while(*tempbuf != '\0')     {         ptr = strrchr(tempbuf,' ');         if(null != ptr)         {              *ptr = '\0';               ptr++;                printf("%s ",ptr);           }          else          {              printf("%s\n",tempbuf);              *tempbuf ='\0';           }     }   

}

test result:

atharv@atharv-inspiron-5423:~/programming$ ./a.out

this long line working with

with working line long this

atharv@atharv-inspiron-5423:~/programming$


Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -