strrev()

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
Eva
New poster
Posts: 14
Joined: Thu Apr 10, 2003 11:31 am
Location: Bombay
Contact:

strrev()

Post by Eva »

This is not supported under the UVA compiler right?

Then what's the fastest code to do this in C/C++?

And if I use standard string class how can I made this?
My own quote:

We are here as Adam and Eve were here!
sohel
Guru
Posts: 856
Joined: Thu Jan 30, 2003 5:50 am
Location: New York

Post by sohel »

To reverse a string I use the following function

[cpp]
string_revers(char str[])
{
int i,l;
char t;
l = strlen(str) - 1;
for(i=0; i<l; i++)
{
t = str;
str = str[l];
str[l] = t;
l--;
}
}
[/cpp]

I don't think there is a faster algorithm than this simple function.
[/c]
mbakht
New poster
Posts: 16
Joined: Fri Feb 28, 2003 7:54 pm
Location: Bangladesh
Contact:

Post by mbakht »

You don't need to go full length of the string. Going upto half the length of the string would be enough :). Doing swap using XOR operation would make it even faster.....though that hardly matters.
CDiMa
Experienced poster
Posts: 214
Joined: Fri Oct 17, 2003 5:49 pm
Location: Genova

Post by CDiMa »

mbakht wrote:You don't need to go full length of the string. Going upto half the length of the string would be enough :). Doing swap using XOR operation would make it even faster.....though that hardly matters.
Actually it goes up to half the lenght... 8)

Ciao!!!

Claudio
mbakht
New poster
Posts: 16
Joined: Fri Feb 28, 2003 7:54 pm
Location: Bangladesh
Contact:

Post by mbakht »

I am extremely sorry. I didn't notice l--.
anupam
A great helper
Posts: 405
Joined: Wed Aug 28, 2002 6:45 pm
Contact:

Post by anupam »

Actually, the beginers ace the problems very much. They normally choose the string problems and use strrev() and get CE.
I got many mail from the beginners about this topic.
--
Anupam
"Everything should be made simple, but not always simpler"
Tahseen Mohammad
Learning poster
Posts: 54
Joined: Sun Oct 28, 2001 2:00 am
Location: Bangladesh

Post by Tahseen Mohammad »

for reversing any sequence you can use the STL algorithm function

std::reverse requries to #include<algorithm>

std::reverse(beginning_iterator, ending_iterator);

so for

Code: Select all

char a[10]; => std::reverse(a, a + 10);
and for

Code: Select all

string s; => std::reverse(s.begin(), s.end());
Or you can always use the handwritten function given by sohel.[/code]
Post Reply

Return to “C++”