首页 > 解决方案 > 我需要帮助交换这个字符串

问题描述

#include <iostream>

using namespace std;

int main()
{
    string sentence;
    string output;
    string product1;
    string product2;
    char pr1;
    string product;
    
    int i;
    getline (cin,sentence);
    char pr2;
    
    cin >> pr1;
    cin >> pr2;
    
    for (i=0; i < sentence.length();i++){
        
        pr1 = sentence[i]; //asdfg---> g
        pr2 = sentence[0]; //--> a 
    }
    
    output += pr1+sentence+pr2;

    cout << output;
    return 0;
}

此代码用于交换字母,但例如当我输入时asdfg我得到gaasdfga. 当我输入它时,我想交换ga. 知道我应该怎么做吗?知道出了什么问题,我该如何改进它?

标签: c++stringloopsswap

解决方案


下面将新值分配给pr1pr2。您输入的字符将丢失。

    pr1 = sentence[i]; //asdfg---> g
    pr2 = sentence[0]; //--> a 

要交换两个输入字符中第一个找到的字符,请使用std::string::find然后std::swap

例子:

#include <utility>
#include <string>
#include <iostream>

int main() {
    std::string sentence = "asdfg";

    char pr1 = 'g';
    char pr2 = 'a';

    auto pos1 = sentence.find(pr1);
    auto pos2 = sentence.find(pr2);

    if(pos1 != sentence.npos && pos2 != sentence.npos) {
        std::swap(sentence[pos1], sentence[pos2]);
    }

    std::cout << sentence << '\n';
}

输出:

gsdfa

另一种方法std::swap(sentence[pos1], sentence[pos2]);是手动进行交换:

char temp = sentence[pos1];
sentence[pos1] = sentence[pos2];
sentence[pos2] = temp;

或通过您调用的用户定义swapper函数,就像您调用的那样std::swap

template<class T>
void swapper(T& lhs, T& rhs) {
    // move construct a temporary variable from the argument on the
    // left hand side
    T temp = std::move(lhs);

    // move assign the left hand side from the right hand side
    lhs = std::move(rhs);

    // move assign the right hand side from the temporary variable
    rhs = std::move(temp);
}

推荐阅读