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

时间:2019-06-09 17:43:51

标签: c++ algorithm loops encryption 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();
}

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

his is a simple string.

2 个答案:

答案 0 :(得分:5)

首先,由于

,您无法访问
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在评论中指出的)。

总共,您可能想要这个

#include <string>

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

答案 1 :(得分:4)

我认为您的目标是:

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
相关问题