如何比较属于同一字符串的 2 个字符

How can I compare 2 characters which belong to the same string?

本文关键字:字符串 字符 属于 何比较 比较      更新时间:2023-10-16
数据类型

是字符串,我想比较该字符串的 2 个字符并交换这两个字符例:字符串 x="ABDCBC">

比较字符后,我想要以下输出:阿布达克

这是一个简单的swap函数:

i1i2参数是索引。它们是您要在str string内交换的角色的位置。

bool swap(string &str, size_t i1, size_t i2)
{
    if (i1 >= str.size() || i2 >= str.size()) // Out of bounds
        return (false);
    char tmp = str[i1];
    str[i1] = str[i2];
    str[i2] = tmp;
    return (true);
}

我做了一个小演示。你可以在这里测试它:https://ideone.com/4OQdib