2012-06-28 41 views
-3

例如,用戶輸入數字542035。應用程序必須從給定數字中刪除所有5 s和0,並打印423。無法弄清楚,簡單的方法來編寫諸如「查找和刪除」數字中的所有0和5的內容?有什麼建議麼?查找並從給定號碼中刪除號碼

+1

您可以將其轉換爲字符串並從那裏開始。 – chris

+1

既然你說過用戶輸入的號碼,它必須已經作爲一個字符串。看看'std :: string'和'std :: remove_if'。這是功課嗎? – Chad

回答

5

將數字轉換爲字符串,執行替換(用「」替換數字),顯示結果。

+0

你能寫一些示例代碼嗎? – heron

+5

@epic_syntax:是的,我可以。你不知道如何將數字轉換爲字符串並在C中執行替換?他們是非常基本的概念,而且互聯網上已經有很多例子。 –

0

下面是一個使用C++ 11的例子。

注:如果這是一門功課的問題,這很可能是老師正在尋找,但它是地道的答案。

#include <string> 
#include <algorithm> 
#include <iostream> 

int main() 
{ 
    std::string s("542035"); 

    std::cout << "Input: " << s << "\n"; 

    auto new_end = std::remove_if(
     s.begin(), 
     s.end(), 
     [] (const char c) -> bool 
    { 
     switch(c) 
     { 
     case '5': 
     case '0': 
     return true; 
     default: 
     return false; 
     } 
    }); 

    s.assign(s.begin(), new_end); 

    std::cout << "Result: " << s << "\n"; 
} 
+0

作爲我的家庭作業答案,我會認爲三思而後行 – Azuan

0

此代碼似乎適用於我這個問題。我不確定它是否是最好的解決方案。

#include <iostream> 
#include <string> 
#include <sstream> 
#include <vector> 
using namespace std; 

int main() 
{ 
int userinput; 

cin >> userinput; 

string s; 

stringstream out; 

out << userinput; 

s = out.str(); 

cout << s << " " << userinput << endl; 

vector<char> editted; 

string::iterator it; 

for (it = s.begin() ; it < s.end(); it++) 
{ 
if ((*it) == '5' || (*it) == '0') 
{} 
else 
editted.push_back((*it)); 
} 

for (int i = 0; i <editted.size(); i++) 
{ 
cout << editted[i] << endl; 
} 

return 0; 
}