【问题标题】:`std::swap` doesn't work as intended in string manipulation`std::swap` 在字符串操作中不能按预期工作
【发布时间】:2019-10-24 07:09:51
【问题描述】:

我试图通过交换两个连续的字母来进行基本的字符串加密。 而且它并没有真正按我的预期工作。

#include <iostream>
#include <string.h>
#include <algorithm>

int main() 
{
    std::string str = "This is a simple string.";
    for (int i = 0; i <= str.length(); i++) {
        std::swap(str[i], str[i + 1]);
    }
    std::cout << str;
    std::cin.get();
}

我实际上想交换两个相邻的字母,所以它看起来像加密的。 当前结果是

his is a simple string.

【问题讨论】:

  • 未定义的行为,因为索引超出了str 的末尾(当i == str.length ()i == str.length () - 1 时)。
  • 这:“ for (int i = 0; i
  • 另外,std::string 的正确标头是 &lt;string&gt;,而不是 &lt;string.h&gt;
  • 更准确地说,这里是dangers of using the incorrect string header。您的程序无法在 Visual Studio 中编译。

标签: c++ algorithm loops encryption stdstring


【解决方案1】:

首先,由于

,您有越界访问权限
for (int i = 0; i <= str.length(); i++) 
//                ^^^^

因此behavior of your program is undefined。 你想迭代一个超过字符串的大小。除此之外,仅当字符串不为空时才循环(credits @jww)。

其次,intunsigend int(即str.length()which is also not you want之间有一个比较。

最后但同样重要的是,为std::string 添加正确的标题(正如@PaulMcKenzie 在 cmets 中指出的那样)。

总的来说,你可能想要这个

#include <string>

for (std::size_t i = 0; !str.empty() && i < str.size()-1; i += 2) {
//   ^^^^^^^^^^^        ^^^^^^^^^^^^        ^^^^^^^^^^^^   ^^^^^
    std::swap(str[i], str[i + 1]);
}

【讨论】:

    【解决方案2】:

    我认为您的目标是:

    std::string str = "This is a simple string.";
    for (int i = 0; i <= str.length()-2; i+=2) 
    {
        std::swap(str[i], str[i + 1]);
    }
    std::cout << str;
    

    有输出

    hTsii  s aispmels rtni.g
    

    【讨论】:

    • 也许像 for (size_t i = 0; !str.empty() &amp;&amp; i &lt; str.length() - 1; i++) 这样也可以处理空消息。
    • 是的......当“str.size()
    猜你喜欢
    • 2012-06-17
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多