A small function which reverses a c-string by just swapping the elements :) ...
Usage::
char[] str = "hello";
reverse(str); // str now contains "olleh"
A small function which reverses a c-string by just swapping the elements :) ...
Usage::
char[] str = "hello";
reverse(str); // str now contains "olleh"
/**********************************
* Written by Mathias Van Malderen *
**********************************/
void reverse(char p[])
{
int len=strlen(p);
char t;
for(int i=(--len), j=0; i>len/2; i--, j++)
{
// exchange elements
t=p[i];
p[i]=p[j];
p[j]=t;
}
}
For C style strings there is <string.h>'s _strrev() and for C++'s strings there's <algorithm>'s reverse().
_strrev() is generally provided in most compilers.
>_strrev() is generally provided in most compilers.
But not on all :P
This is how it would look like if you asked me to rewrite it:
void reverse(char *p)
{
char *q = p + strlen(p) - 1;
for(; p < q; p++, q--)
{
char c = *p;
*p = *q;
*q = c;
}
}
(no NULL-pointer check included).
make program in c language by using for loop to show
3
323
32123
323
3
I would do this a bit different:
void reverse(char p[])
{
int len=strlen(p);
for(int i=0, i<len/2; i++)
{
// exchange elements
p[i]^=p[len - i - 1];
p[len - i - 1]^=p[i];
p[i]^=p[len - i - 1];
}
}
Your code snippet can be shortened tux...here it goes:
void reverse(char p[])
{
int len=strlen(p);
for(int i=len-1, j=0;j<i; i--, j++)
{
// exchange elements
p[i]^=p[j]^=p[i]^=p[j];
}
}
Try it and do tell me what do you think...???
Sorry about the reply... I didn't see it was a 6 month old thread resurrected... just answered it... ;)
All I wanted just reduce the number of local variables.
Your line “p^=p[j]^=p^=p[j];” in most of compilers has “undefined behaviour”.
Just try to swap to integers a = 0x55 and b = 0xAA your way (a ^= b ^= a ^= b;) using different compilers.
>Sorry about the reply... I didn't see it was a 6 month old thread resurrected... just answered it...
Never mind, any input is welcome.
>All I wanted just reduce the number of local variables.
Yes, I see, though the algorithm of reversing the string is basically the same, I hadn't thought of the the fact that I could use XOR-operations to swap the values without having to use a temporary variable.
Nice suggestion :)
@vitkaodessit: please post your code using code tags the next time.
>>All I wanted just reduce the number of local variables.
>Yes, I see, though the algorithm of reversing the string is basically the same,
>I hadn't thought of the the fact that I could use XOR-operations to swap the values without having to use a temporary variable.
>Nice suggestion
Although this eliminates the extra variable, it can cause undefined behavior. For some reason, some teachers insist on learning their student this 'xor swap method', but I would strongly advice against it.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.