交换字符串数组中的字符

时间:2016-05-03 02:11:24

标签: c++

尝试反转交换字符串数组中的所有字符,但是,它没有正确输出。有谁知道我是否正朝着正确的方向前进?

我的代码:

#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交换?

1 个答案:

答案 0 :(得分:0)

试试这个:

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