Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
If the input is "I Love India"
then the output is "I evoL aidnI"
in C programming
Posted
Updated 6-Oct-13 13:02pm
v2
Comments
Mehdi Gholam 5-Oct-13 4:54am    
Looks like homework.
Hemant Singh Rautela 5-Oct-13 5:34am    
it is defiantly homework... :-)
MuhammadUSman1 5-Oct-13 7:00am    
Please check my solution.

Refer this link and before that put your effort in learning. Try to make your own logic and implement by referring some articles.

http://www.programmingsimplified.com/c/source-code/reverse-words-in-string[^]
 
Share this answer
 
How about using strcspn and strlen:
C
...
char str[] = "...";     // your line to transform inplace
const char sep[] = " "; // you name the separators here, many more?
int len = 0;
char *word = str;
while(NULL != (word = next_word(sep, word, &len))) swap_wordchars(word, len)
printf("%s", str);


C
int next_word(char *sep, char *word, int *len)
{
   // move forward behind the last match
   word += *len;
   // get length until separator or until end of text (try until no leading sep)
   while(0 == (*len = strcspn(word, sep)) && *word) word++;
   // no more data: NULL
   return *len ? word : NULL;
}


C
void swap_wordchars(char* str, int len)
{
   int sentry = len / 2;
   for(int i = 0; i < sentry; ++i) swap_chars(str+i, str+len-1-i);
}


C
void swap_chars(char *a, char *b)
{
    char c = *a;
    *a = *b;
    *b = c;
}


I did now half of your homework - you have to do some boiler plate coding (add appropriate includes and the main function), compile, link, run.
And you might need to explain the code to someone ;-)

Cheers
Andi
 
Share this answer
 
v3
 
Share this answer
 
It is solution for your question.

ROT13
 
Share this answer
 
Comments
Manfred Rudolf Bihy 6-Oct-13 19:24pm    
Now what exactly does a ROT13 cipher have to do with reversing words within a string.
You seem to be even more confused than OP.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900