I am working on a project and I am facing a problem. I need to find a set of characters in a string like if user enters his/her email then i have to check whether the email is correct or not. I am finding it to use the string class find
function but i haven't succeeded. I can use the loop to find the last character but I and looking for a simplest method to work for it. Example: email@gmail.com
I want to get .com
as the last characters of string.
Here is the code of mine:
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;
}
You can use std::string::substr
to first get the last 4 characters as an std::string
, then you can compare it with ".com":
std::string email = "example@mail.com";
std::string ext = email.substr(email.length() - 4, 4);
bool check = ext == ".com";
To check if it was not found:
if (str.find_last_of(".com")==std::string::npos){
check = false;
}
To check if it was found:
if (str.find_last_of(".com")!=std::string::npos){
check = false;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.