reverse a string - word by word - revisited
Hmm, I agree that swapping the string and
then swapping each word is probably the
best solution, but I would disagree that
swapping the words is impossible (or even
that hard or obscure). The obvious (if
somewhat nasty) solution is to create a
linked list, traverse the string forwards
adding a pointer to each word to the linked
list, and then simply traverse the list
backwards adding the words to the new string
as you go.
I can't leave statements like "impossible"
alone heh :)
Tuesday, November 26, 2002
You are forgetting that the problem required that the string be reversed in place.
Apart from a couple of pointers, the original solution (reverse the string in place, then reverse the words in place) requires only an extra sizeof(char) to temporarily buffer a single character as characters are swapped.
Saturday, November 30, 2002
The extra char is unnecessary as well. Using integer arithmetic, this code snippet will change two characters in situ:
a=a xor b
b=a xor b
a=a xor b
Tuesday, December 3, 2002
xor's are for sissies:
a = a+b
b = a-b
a = a-b
Monday, December 30, 2002
Fog Creek Home