`std :: swap`不能按预期的那样在字符串处理中工作

Ali*_*yer 3 c++ encryption algorithm loops stdstring

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

#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();
}
Run Code Online (Sandbox Code Playgroud)

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

his is a simple string.
Run Code Online (Sandbox Code Playgroud)

JeJ*_*eJo 5

首先,您由于以下原因而无法访问

for (int i = 0; i <= str.length(); i++) 
//                ^^^^
Run Code Online (Sandbox Code Playgroud)

因此,您的程序行为是不确定的。您想迭代一个超过字符串大小的位置。除此之外,仅当字符串不为空时循环(鸣谢@jww)。

其次,int和之间没有比较unsigend int(即str.length(),这也是您不想要的

最后但并非最不重要的一点是,添加正确的标头std::string如@PaulMcKenzie在评论中指出的)。

总共,您可能想要这个

#include <string>

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