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];
}
}
- When
i
is0
you'll be accessingstring[len]
which is incorrect as the valid index in an array of lengthlen
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:
- You are not swapping.
- Also the swapping should happen for one half of the array, not for the entire array.
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]);
}
First of all, you would get an error on line 6.
Change the {
into }
. Then try again.
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.
This is tagged C++, do it the C++ way...
std::string ReverseString(std::string str)
{
std::reverse(str.begin(), str.end());
return str;
}
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];
}
}
精彩评论