/** PIE Reverse words in string "I do like NFL" -> "NFL like do I" **/ void ReverseWords(char str[]){ int str_len = 0; str_len = strlen(str); //char *reversed = malloc(sizeof(char)*str_len); ReverseStr(str,str_len); char *current_str; int start = 0; strlen = 0; while(str[strlen+start]!='\0'){ strlen = 0; while(str[strlen+start]!=' '){ strlen++; } current_str = str + start; ReverseStr(current_str,strlen); start += strlen+1; //skip space; } }
Method2 #include <stdio.h> #include <malloc.h> #include <string.h> void ReverseStr ( char *buff, int start, int end ) { char tmp ; if ( start >= end ) { printf ( "\n%s\n", buff ); return; } tmp = *(buff + start); *(buff + start) = *(buff + end); *(buff + end) = tmp ; ReverseStr (buff, ++start, --end ); }
int main() { char buffer[]="This is Test"; ReverseStr(buffer,0,strlen(buffer)-1); return 0; }