首页 > 解决方案 > 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 循环,但我不确定我应该在括号内放什么。

标签: c++iostream

解决方案


这涵盖了@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";
}

推荐阅读