[英]How to find a set of characters in a string
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.我发现它使用字符串类find
函数,但我没有成功。 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.示例: email@gmail.com
我想将.com
作为字符串的最后一个字符。
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::substr
首先将最后 4 个字符作为std::string
,然后您可以将其与“.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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.