开发者

Am I missing something in my function?

开发者 https://www.devze.com 2023-01-30 13:39 出处:网络
This is what I have so far and I keep getting an error. Any help? void ReverseString(char* string) { int len = strlen(string);开发者_如何学编程

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 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:

  • 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];  
    }  
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消