c++ - 我需要帮助交换这个字符串
问题描述
#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
. 当我输入它时,我想交换g
和a
. 知道我应该怎么做吗?知道出了什么问题,我该如何改进它?
解决方案
下面将新值分配给pr1
和pr2
。您输入的字符将丢失。
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);
}
推荐阅读
- python - 给定来自均匀分布 [0,d] 的 n 个样本,你将如何估计 d?
- ruby-on-rails - 需要帮助使用 rubyzip 和 rails 创建 zip 文件存档
- python - 如何通过“link_text”找到这个元素?
- postgresql - Postgresql ODBC AutoCommit 模式的真正含义是什么
- c - 将 MINIX 扩展策略从使用 FCFS 的优先级更改为使用 SJF 的优先级
- sqlalchemy - 在 sqlalchemy 中实现窗口函数时需要帮助
- node.js - 如何使用枚举来确定有条件的打字稿返回值?
- python - 如何排除已在先前循环迭代中使用的生成随机对?
- django - Django 查询集分组和计数相关字段
- c++ - X11 Copy 只返回 GDK_SELECTION,用于剪贴板选择