删除在两个字符串的比较中不常见的字符

Removing characters that are uncommon in the comparison of two strings

本文关键字:比较 不常见 字符 字符串 两个 删除      更新时间:2023-10-16
string word1 = "misisipi";
string word2 = "mississippi";

我想"比较"这些字符串,并能够"扔掉"不常见的字母。例如,word2将被削减为"misisipi",确保保持'S'的顺序,并且word1不会改变,因为它的所有字符都在word2。 我知道如何删除字符串中的元素,但这次我想保持顺序。 例如,如果我维护订单,经过比较,word2将是"missipi",这不是我想要的。

尝试在

循环访问word1的每个元素时将有效的word2字符复制到word1中。

std::string temp;
std::string::iterator w2 = word2.begin();
for(std::string::iterator w1 = word1.begin(); w1 != word1.end(); ++w1)
{
    for(; w2 != word2.end(); ++w2)    // Move through word2...
    {
        if(*w1 == *w2)    // Copy the character into temp when found.
        {
            temp += *w2;
            break;
        }
    }
}
std::cout << temp << std::endl;

如果您想要速度,可能需要事先分配temp