Skip to content

Instantly share code, notes, and snippets.

@lexich
Created July 11, 2012 18:48
Show Gist options
  • Save lexich/3092329 to your computer and use it in GitHub Desktop.
Save lexich/3092329 to your computer and use it in GitHub Desktop.
revert C-string without temp
#include <string.h>
#include <stdio.h>
/*
revert buffer C-string without temp
abc\0 -> cba\0
@str buffer
@len size of buffer
*/
void revert(char* str, int len ){
for( int i = 0, e = len - 2; i < e; ++i, --e ){
*(str + i) ^= *(str + e);
*(str + e) ^= *(str + i);
*(str + i) ^= *(str + e);
}
}
int main(int argc, char const *argv[])
{
char testString[] = "Test string";
int len = sizeof(testString)/sizeof(char);
char* str = new char[len];
strcpy(str, testString);
printf("%s\n", str);
revert(str, len);
printf("%s\n", str);
delete [] str;
return 0;
}
@lexich
Copy link
Author

lexich commented Jul 11, 2012

g++ -Wall -pedantic -O3 -o exch revert.cpp && revert

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment