簡體   English   中英

如何在字符串中查找一組字符

[英]How to find a set of characters in a string

我正在做一個項目,但遇到了一個問題。 我需要在字符串中找到一組字符,比如如果用戶輸入他/她的電子郵件,那么我必須檢查電子郵件是否正確。 我發現它使用字符串類find函數,但我沒有成功。 我可以使用循環來查找最后一個字符,但我正在尋找一種最簡單的方法來處理它。 示例: email@gmail.com我想將.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;
}

您可以使用std::string::substr首先將最后 4 個字符作為std::string ,然后您可以將其與“.com”進行比較:

std::string email = "example@mail.com";
std::string ext = email.substr(email.length() - 4, 4);
bool check = ext == ".com";

要檢查它是否找到:

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

要檢查它是否找到:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM