How do you reverse a string in C or C++ without requiring a separate buffer to hold the reversed string?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The standard algorithm is to use pointers to the start / end, and walk them inward until they meet or cross in the middle. Swap as you go.
Reverse ASCII string, i.e. a 0-terminated array where every character fits in 1
char. (Or other non-multibyte character sets).The same algorithm works for integer arrays with known length, just use
tail = start + length - 1instead of the end-finding loop.(Editor’s note: this answer originally used XOR-swap for this simple version, too. Fixed for the benefit of future readers of this popular question. XOR-swap is highly not recommended; hard to read and making your code compile less efficiently. You can see on the Godbolt compiler explorer how much more complicated the asm loop body is when xor-swap is compiled for x86-64 with gcc -O3.)
Ok, fine, let’s fix the UTF-8 chars…
(This is XOR-swap thing. Take care to note that you must avoid swapping with self, because if
*pand*qare the same location you’ll zero it with a^a==0. XOR-swap depends on having two distinct locations, using them each as temporary storage.)Editor’s note: you can replace SWP with a safe inline function using a tmp variable.
Examples: