c++ - ASCII 字符串组合
问题描述
我正在开发一个程序来根据字母表的 ASCII 顺序组合两个字符串,并删除所有重复的字母。到目前为止我有
#include <iostream>
using namespace std;
int main() {
string s1, s2;
string combined;
while (true) {
cin >> s1 >> s2;
if (s1 == "quit" && s2 == "quit") break;
cout << "Read " << "\"" << s1 << "\"" << " and " << "\"" << s2 << "\" -> ";
combined = s1+s2;
cout << combined << endl;
}
cout << "Bye";
return 0;
}
输出应该看起来像Read "binarytriangle" and "ANSIStandard" -> "AINSabdegilnrty"
,但我似乎无法弄清楚如何根据字母顺序实际组合它们并删除重复的字母。char
在网上我只找到了如何根据ASCII顺序而不是对两个字符串进行排序来获取a的数值。我正在考虑使用 for 循环,但我不确定我应该在括号内放什么。
解决方案
这涵盖了@molbdnilo 在评论中写的内容,但在代码中带有内联评论。这部分:
while (true) {
cin >> s1 >> s2;
是一个潜在的陷阱。如果写入端关闭流,您将最终陷入无限循环。此外,使用命名空间标准;是一种不好的做法。
#include <iostream>
#include <algorithm> // std::sort
// Dont do this:
// using namespace std;
int main() {
std::string s1, s2;
std::string combined;
// check if std::cin is true in a boolean context after having tried to extract
// the strings. If it's not true, you'll may end up with an endless loop (if
// the writing side closed the stream).
while(std::cin >> s1 >> s2) {
if(s1 == "quit" && s2 == "quit") break;
std::cout << "Read "
<< "\"" << s1 << "\""
<< " and "
<< "\"" << s2 << "\" -> ";
combined = s1 + s2;
// sort the chars in the string.
std::sort(combined.begin(), combined.end());
// move repeated chars to the end of the string and return an iterator to
// what will become the new end of the string
std::string::iterator new_end = std::unique(combined.begin(), combined.end());
// the string is just as long as before here, but all the repeated chars
// are at the end, so,
// erase all chars from new_end to current end()
combined.erase(new_end, combined.end());
std::cout << combined << "\n"; // std::endl for flushing is unncessary in most cases
}
std::cout << "Bye\n";
}
推荐阅读
- linux - 如何为在随机端口上运行的自定义程序启用 Linux 防火墙(ufw)
- javascript - 使用通用的单个提交按钮提交多个表单时如何创建单个请求
- mysql - 识别两列之间的连接并插入相应的值
- python - Koalas 与 Sklearn 不兼容 - ValueError: could not convert string to float: 'x'
- http - HTTP 请求未在响应中执行 - Flutter/Dart
- pyomo - 如何在 pyomo 抽象模型中实例化索引块,参数用块外的索引索引?
- firebase - 从fabric迁移后如何在firebase crashlytics中创建团队?
- webhooks - 发布文档时从 Sanity 接收 webhook 或其他类型的 ping?
- android - 自定义 AlertDialog 有时不会在 UI 上显示,为什么?
- javascript - 将消息从一个选项卡发送到另一个选项卡