Reverse words in a sentense keeping space positions same

biswajit.dash's Avatar
Light Poster

I have been try this for 2-3 hr.

what my intent is to hav program while will reverse the words in a sentence without changing the space positions.


input: char str[]="My name is Biswajit""
output : "Biswajit is name My"

I m successful in reversing the words without keeping the space positions same, i m not successful in other way.

Appreciate any thoughts.

xpi0t0s's Avatar, Join Date: Aug 2004
Scan right to left checking for spaces and counting the length of the word you're currently looking at.
Then use strncpy to copy a fixed number of characters to the end of the output string.
Remember to add spaces too.

Another way to do it is to create a substring reverser that will reverse the specified characters within a string (for example, if you gave it "abcde", start position 1, number of characters 3, it would change the string to "adcbe"). Then reverse the whole string, and use the substring reverser to reverse each individual word.
CrazyGeek's Avatar, Join Date: Jun 2010
Newbie Member
I think It's simpler if you use the function gotoxy(x,y);
At first call gotoxy(x,y) to move text pointer to a position that the distance to home line is long enough to show your string.
Then scan through all characters of your string and print one by one, if the charater is " " ( means a space), call gotoxy(x,y) to the appropriate position.( the text pointer must be back everytime you catch a space). I know you can understand my idea. OK thanks!
xpi0t0s's Avatar, Join Date: Aug 2004
Good idea, except that gotoxy moves the cursor on the screen and has absolutely bu99er all to do with string manipulation.