Skip to content

Instantly share code, notes, and snippets.

@KrzysztofCiba
Created February 6, 2013 22:08
Show Gist options
  • Save KrzysztofCiba/4726337 to your computer and use it in GitHub Desktop.
Save KrzysztofCiba/4726337 to your computer and use it in GitHub Desktop.
revert words ina sentence C
#include <stdio.h>
void revertWord( char *start, char *end ) {
char temp;
while( start < end ) {
temp = *start;
*start = *end;
*end = temp;
++start;
--end;
}
}
void revertString(char *sentence) {
char *start = sentence;
char *end = sentence;
while ( *(++end) ); // to the null
// but don't touch not null
--end;
// all sentence first
revertWord( start, end );
// and now word by word
while ( *start ) { // not null?
// find space if any, move start to it
for (; *start && *start == ' '; ++start );
// find end fo the word, move end to it
for ( end = start; *end && *end != ' '; ++end );
// space or null, back one
--end;
// reverse from start to end
revertWord( start, end );
// next word or null
start = ++end;
}
}
int main() {
char test[] = "The quick brown fox jumped over the lazy dog.";
printf( "before: %s\n", test );
revertString(test);
printf( "after: %s\n", test );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment