我的函数中是否缺少某些内容?

发布于 2024-10-07 20:46:47 字数 214 浏览 0 评论 0原文

这就是我到目前为止所拥有的,但我不断收到错误。有什么帮助吗?

void ReverseString(char* string) {
    int len = strlen(string);
    for(int i = 0; i < len; i++)
    {
         string[i] = string[len-i];
    }
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

忘羡 2024-10-14 20:46:47
  • i0 时,您将访问
    string[len] 这是不正确的
    长度数组中的有效索引
    len[0,len-1]

如果我正确理解您的意图,您正在尝试反转字符串,但我可以看到缺少一些东西:

  • 您没有交换。
  • 交换也应该发生
    数组的一半,不适合
    整个阵列。

以下代码片段修复了这些问题:

int len = strlen(string);
for(int i = 0; i < len/2; i++) {
    swap(string[len-i-1],string[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]);
}
森林迷了鹿 2024-10-14 20:46:47

首先,您会在第 6 行收到错误。

{ 更改为 }。然后再试一次。

First of all, you would get an error on line 6.

Change the { into }. Then try again.

‖放下 2024-10-14 20:46:47

除了两个已经提到的错误之外:

您将从原始字符串中生成回文。上半场将等于下半场逆转。不过,下半场将保持不变。这不是函数名称所声明的内容。

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.

冬天的雪花 2024-10-14 20:46:47

这是标记为 C++ 的,用 C++ 的方式来做......

std::string ReverseString(std::string str) 
{
  std::reverse(str.begin(), str.end());
  return str;
}

This is tagged C++, do it the C++ way...

std::string ReverseString(std::string str) 
{
  std::reverse(str.begin(), str.end());
  return str;
}
尛丟丟 2024-10-14 20:46:47

应该是 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];  
    }  
} 

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];  
    }  
} 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文