正在交换字符串数组中的字符

Swapping characters in string array

本文关键字:字符 数组 字符串 交换      更新时间:2023-10-16

试图反向交换字符串数组中的所有字符,但输出不正确。有人知道我的方向是否正确吗?

我的代码:

#include <string>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <cstring> // for strlen()
using namespace std;
void doSwap (char &string1, char &string2) {
    char temp;
    temp = string1;
    string1 = string2;
    string2 = temp;
}
int main() {
    string testingWord = "hello";
    int i;
    cout << testingWord << "n";
    cout << "tBelow is testing the swap feature:n";
    for (i = 0; i < testingWord.size() - 1; i++) {
        doSwap(testingWord[i], testingWord[i+1]);
    }
    cout << testingWord << "n";
}

这是我的输出:

elloh

编辑:不尝试进行XOR交换?

试试这个:

for (i = 0; i < testingWord.size() / 2; i++) {
    doSwap(testingWord[i], testingWord[testingWord.size() - i]);
}