Skip to content

Instantly share code, notes, and snippets.

@jitsceait
Last active August 29, 2015 14:00
Show Gist options
  • Select an option

  • Save jitsceait/81d02e24ff89c876ca1e to your computer and use it in GitHub Desktop.

Select an option

Save jitsceait/81d02e24ff89c876ca1e to your computer and use it in GitHub Desktop.
Program to reverse words in string
#include <stdio.h>
#include <stdlib.h>
/* This function reverses the whole string */
void reverse(char s[]){
int i=0, j;
int end = strlen(s);
for(i=0, j=end-1; i<j; i++, j--){
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
/* This function reverses a given word, we need to provide stat and end of the word */
void reverse_word(char * start, char * end){
while(start < end){
char temp = *start;
*start++ = *end;
*end-- = temp;
}
}
void reverse_words(char *string){
char * source = string;
char *begin = string;
if(string == NULL) return;
/* Step 1 : Reverse the whole string */
reverse(string);
/* Now reverse individual words in reversed string */
while(*source != '\0'){
if(*(source +1) == ' ') {
reverse_word(begin, source);
begin = source + 2;
source++;
}
/*Case when it is last word of string */
else if(*(source + 1) == '\0'){
reverse_word(begin, source);
}
source++;
}
}
/* driver program to run above code */
#define MAX_LENGTH 100
int main(){
char string[MAX_LENGTH] = "This is a test string";
reverse_words(string);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment