|
-
Sep 14th, 2001, 06:36 AM
#1
Thread Starter
Lively Member
tring function
hello
can anyone write me a function for string reversal
without using string functions and without using a temporary
character array
to store the reversed string
-
Sep 14th, 2001, 07:20 AM
#2
Frenzied Member
This code will only work in release mode if you're using VC++6. I don't know why, but VC++6 probably protects memory writes to make debugging easier or something. Anyway it works in release mode.
Code:
#include <iostream>
char *revstr(char *str)
{
int length = strlen(str)-1;
char *pstrstart = str;
char *pstrend = str + length;
while((pstrend - pstrstart) > 0)
{
//swap characters
*pstrstart = *pstrstart ^ *pstrend;
*pstrend = *pstrstart ^ *pstrend;
*pstrstart = *pstrstart ^ *pstrend;
pstrstart++;
pstrend--;
}
return str;
}
int main()
{
char *str = "abcde";
std::cout << "revstr(\"abcde\") => " << revstr(str) << std::endl;
return 0;
}
Harry.
"From one thing, know ten thousand things."
-
Sep 14th, 2001, 07:42 AM
#3
Frenzied Member
Oops, just realised I had a string function in there (strlen).
Here's the alternative:
Code:
#include <iostream>
char *revstr(char *str)
{
char *pstrstart = str;
char *pstrend = str;
while(*(pstrend+1) != '\0')
pstrend++;
int length = pstrend - pstrstart-1;
while((pstrend - pstrstart) > 0)
{
//swap characters
*pstrstart = *pstrstart ^ *pstrend;
*pstrend = *pstrstart ^ *pstrend;
*pstrstart = *pstrstart ^ *pstrend;
pstrstart++;
pstrend--;
}
return str;
}
int main()
{
char *str = "abcde";
std::cout << "revstr(\"abcde\") => " << revstr(str) << std::endl;
return 0;
}
Harry.
"From one thing, know ten thousand things."
-
Sep 14th, 2001, 07:55 AM
#4
Thread Starter
Lively Member
thanks
thank you HarryW
it is fine
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|