[英]I need help swapping this string
#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;
}
This code is made to swap letters, but for example when I enter asdfg
I get gaasdfga
.此代码用于交换字母,但例如,当我输入
asdfg
我得到gaasdfga
。 When I enter that, I want to swap g
and a
.当我输入时,我想交换
g
和a
。 Any idea what I should do?知道我应该做什么吗? Any idea what's wrong, and how I can improve it?
知道出了什么问题,我该如何改进?
The below assigns new values to pr1
and pr2
.下面为
pr1
和pr2
分配新值。 The characters you entered will be lost.您输入的字符将丢失。
pr1 = sentence[i]; //asdfg---> g
pr2 = sentence[0]; //--> a
To swap the first found of each of the two entered characters, use std::string::find
and then std::swap
要交换两个输入字符中第一个找到的字符,请使用
std::string::find
然后使用std::swap
Example:例子:
#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';
}
Output:输出:
gsdfa
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.