Reputation: 607
This is what I have so far and I keep getting an error. Any help?
void ReverseString(char* string) {
int len = strlen(string);
for(int i = 0; i < len; i++)
{
string[i] = string[len-i];
}
}
Upvotes: 2
Views: 127
Reputation: 7769
should be string[i] = string[len-i-1];
// added (untested):
void ReverseString(char * string) {
int len = strlen(string);
for(int i = 0; i < len / 2; i++)
{
string[i] ^= string[len-i-1];
string[len-i-1] ^= string[i];
string[i] ^= string[len-i-1];
}
}
Upvotes: 0
Reputation: 33645
This is tagged C++, do it the C++ way...
std::string ReverseString(std::string str)
{
std::reverse(str.begin(), str.end());
return str;
}
Upvotes: 1
Reputation: 455192
i
is 0
you'll be accessing
string[len]
which is incorrect as
the valid index in an array of length
len
are [0,len-1]
If I understand you intent correctly you are trying to reverse the string but I can see a few things missing:
The following snippet fixes these issues:
int len = strlen(string);
for(int i = 0; i < len/2; i++) {
swap(string[len-i-1],string[i]);
}
Upvotes: 6
Reputation: 14890
Besides two already mentioned errors:
You'll make a palindrom out of the original string. The first half will became equal to second half inversed. However, the second half will remain the same. This is not what the function name declares.
Upvotes: 1
Reputation: 7716
First of all, you would get an error on line 6.
Change the {
into }
. Then try again.
Upvotes: 2