ASCII字符串组合

时间:2019-03-28 15:13:20

标签: c++ iostream

我正在研究一个程序,根据字母的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循环,但是我不确定应该在括号内放什么。

1 个答案:

答案 0 :(得分:0)

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