2016-05-12 78 views
-2

我正在開發一個項目,並且遇到問題。我需要在字符串中找到一組字符,就像用戶輸入他/她的電子郵件一樣,然後我必須檢查電子郵件是否正確。我發現它使用字符串類find函數,但我沒有成功。我可以使用循環找到最後一個字符,但是我正在尋找最簡單的方法來處理它。 例如:[email protected]我想獲得.com作爲字符串的最後一個字符。如何在字符串中找到一組字符

這裏是我的代碼:

string checkEmail(const char* const prompt) { 
    string str; 
    bool check = true; 
    do { 
     cout << prompt << " : "; 
     cin >> str; 
     if (str.find_last_of(".com")) // here is the error, I think 
      check = false; 
    } while (check); 
    return str; 
} 
+0

我沒有看到任何代碼,您使用'str.find'的結果子集串 – EdChum

+0

我不明白的問題非常好,你想檢查輸入字符串是以「.com」結尾嗎,還是你想從字符串中得到最後幾個字符? –

+0

@FatihBAKIR是的,你說得對。我想找到一個字符串的最後4個字符來檢查它是否是'.com'。 –

回答

0

您可以使用std::string::substr首先得到最後4個字符爲std::string,那麼你就可以用 「.COM」 比較一下:

std::string email = "[email protected]"; 
std::string ext = email.substr(email.length() - 4, 4); 
bool check = ext == ".com"; 
+0

這是有效的!非常有幫助:) –

0

檢查是否爲不是找到:

if (str.find_last_of(".com")==std::string::npos){ 
    check = false; 
} 

要檢查它是否發現:

if (str.find_last_of(".com")!=std::string::npos){ 
    check = false; 
} 
+0

嗯,你確定'x.com.yyy'會是一個有效的結果嗎? –

+0

http://cpp.sh/6ri7i –

+0

@SergeBallesta這就是爲什麼我正在尋找這樣的解決方案,將檢查是否只有'.com'子串在最後是否在這裏? –

相關問題