我正在研究一个程序,根据字母表的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"
但我似乎无法弄清楚如何根据字母顺序实际组合它们并删除重复的字母。在线我只找到了如何根据ASCII顺序获取char
的数值而不是排序两个字符串。我正在考虑使用for循环,但我不确定我应该在括号内放什么。
这包括@molbdnilo在评论中写的内容,但在代码中使用内联注释。这部分:
while (true) {
cin >> s1 >> s2;
是一个潜在的陷阱。如果写作侧关闭流,你将最终得到一个无限循环。此外,using namespace std;是一个不好的做法。
#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";
}