In-place reverse a char* string, in-place reverse word order of char* string

Premable
As a pure coding exercise here are examples of code to reverse a string and reverse the word order.

In-place reverse a string
The reversal of the string using the xor trick. https://en.wikipedia.org/wiki/XOR_swap_algorithm
[js]
//In-place reverse
void reverse(char* s)
{
char* forwards = s;
char* backwards = s;

for(; *backwards != ‘\0’; ++backwards);
–backwards;
while(forwards < backwards) { *forwards = *forwards ^ *backwards; *backwards = *forwards ^ *backwards; *forwards = *forwards ^ *backwards; ++forwards; --backwards; } } [/js] This code does not use additional memory, but is horrendously slow, as not only accessing individual bytes but uses bitwise operations as well. This solution is not recommended for any large processor, possibly only useful in embedded systems using 8-bit micro-controller. CPU much prefer working in bigger byte blocks. Better to use SSE registers, see example: https://stackoverflow.com/questions/19627181/reverse-a-string-using-sse

Generally would rather use stl as this reduces the level of complexity, and gives any performance benefits stl can give.
[js]
void reverse2(char* s)
{
char* sEnd = s + strlen(s);
std::reverse(s, sEnd);
}
[/js]

In-place reverse word order
This consists of reversing the entire string, then iterating the string again reversing the individual words which are separated by spaces, hence making the words forward facing and readable again.

[js]
//In-place reverse words
void reverseWords(char* s)
{
reverse(s);

char* b = s;
char* e = s;

for(;*e != ‘\0’; ++e)
{
if(*e == ‘ ‘)
{
*e = ‘\0’;
reverse(b);
*e = ‘ ‘;
b = e;
++b;
}
}

reverse(b);
}
[/js]

Code in full
[js]
#include
#include
#include

using namespace std;

//In-place reverse
void reverse(char* s)
{
char* forwards = s;
char* backwards = s;

for(; *backwards != ‘\0’; ++backwards);
–backwards;
while(forwards < backwards) { *forwards = *forwards ^ *backwards; *backwards = *forwards ^ *backwards; *forwards = *forwards ^ *backwards; ++forwards; --backwards; } } //In-place reverse words void reverseWords(char* s) { reverse(s); char* b = s; char* e = s; for(;*e != '\0'; ++e) { if(*e == ' ') { *e = '\0'; reverse(b); *e = ' '; b = e; ++b; } } reverse(b); } void reverse2(char* s) { char* sEnd = s + strlen(s); std::reverse(s, sEnd); } int main() { { char s[100]; strcpy(s, "abcdefghi"); cout << s << endl; reverse(s); cout << s << endl; reverse2(s); cout << s << endl; } { char s[100]; strcpy(s, "The quick brown fox"); cout << s << endl; reverseWords(s); cout << s << endl; } return 0; } [/js]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.