By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,688 Members | 1,888 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,688 IT Pros & Developers. It's quick & easy.

string reversal

P: 39
Hi.How can a string be reversed without using a loop?thanks for any help.

Jerico
Oct 11 '06 #1
Share this Question
Share on Google+
3 Replies


arne
Expert 100+
P: 315
Hi.How can a string be reversed without using a loop?thanks for any help.

Jerico
You mean something like

string string_reverse( const string& s ) {
string ret;
copy( s.rbegin(), s.rend(), back_inserter( ret ) );
return ret;
}
Oct 11 '06 #2

P: 22
You mean something like

string string_reverse( const string& s ) {
string ret;
copy( s.rbegin(), s.rend(), back_inserter( ret ) );
return ret;
}

If you want to avoid for loop or while loop then you have to use recursion

void str_reverse(char str[],int startIndex,int endIndex)
{
if(startIndex >= endIndex) return;
str_reverse(str,++startIndex,--endIndex);
str[startIndex-1]^=str[endIndex]^=str[startIndex-1]^=str[endIndex];
}
int main(int argc,char* argv[])
{
char str[] = "MyString";
str_reverse(str,0,strlen(str));
printf("%s\n",str);
return 0;
}
Oct 11 '06 #3

100+
P: 293
D_C
Just a hint, any tail end recursion can be converted into a while loop, and that's precisely what most (all?) compilers do.
Oct 11 '06 #4

Post your reply

Sign in to post your reply or Sign up for a free account.