2012-04-11 40 views
0
string word1 = "misisipi"; 
string word2 = "mississippi"; 

我想'比較'這些字符串的一些方法,並能夠'拋出'不常見的字母。 例如,word2將被減少到"misisipi",確保保持'S'es順序,並且word1不會改變,因爲它的所有字符都在word2。我承認如何刪除字符串中的元素,但是這次我想維護這個順序。例如,如果我沒有維持秩序,之後比較word2"missipi",這不是我想要的。刪除在兩個字符串比較中不常見的字符

+4

請發佈您嘗試的代碼幾乎可行。 – 2012-04-11 01:26:49

回答

0

嘗試有效word2字符複製到word1當你通過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事前,如果你想要的速度。

+0

謝謝你的幫助! – 2012-04-11 02:57:08