问题描述如图所示,要求使用c++面向对象的程序设计方法,写出以下问题的完整代码
#include <iostream>
#include <string>
using namespace std;
bool isValidEmail(string email) {
// 查找@和.的位置
int atPos = email.find('@');
int dotPos = email.find('.');
// 判断@和.的位置是否合法
if (atPos == string::npos || dotPos == string::npos ||
atPos == 0 || dotPos == email.length() - 1 ||
dotPos - atPos <= 1) {
return false;
}
// 判断@之前的部分是否合法
string username = email.substr(0, atPos);
for (char c : username) {
if (!isalnum(c) && c != '_' && c != '-') {
return false;
}
}
// 判断@之后的部分是否合法
string domain = email.substr(atPos + 1, dotPos - atPos - 1);
for (char c : domain) {
if (!isalnum(c) && c != '_' && c != '-') {
return false;
}
}
// 判断.com是否合法
string com = email.substr(dotPos + 1);
if (com != "com") {
return false;
}
return true;
}
int main() {
string email;
cin >> email;
if (isValidEmail(email)) {
cout << "yes" << endl;
} else {
cout << "no" << endl;
}
return 0;
}
上面的代码中,isValidEmail函数用于判断电子邮件地址是否合法。首先使用string类的find方法查找@和.字符的位置,然后根据要求进行判断。最后,使用substr方法分别获取@之前和@之后的部分,并判断它们是否合法。如果所有条件都符合,则返回true,否则返回false。
在主函数中,先读入一个字符串,然后调用isValidEmail函数进行判断,最后输出结果。
#include <iostream>
#include <string>
#include <regex>
using namespace std;
class EmailValidator {
public:
// 构造函数
EmailValidator(string email) : email_(email) {}
// 成员函数:判断电子邮件地址是否合法
bool isValidEmail() {
regex pattern("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
return regex_match(email_, pattern);
}
// 析构函数
~EmailValidator() {
cout << "EmailValidator object is destroyed" << endl;
}
private:
string email_;
};
int main() {
string email;
cin >> email;
// 创建 EmailValidator 对象时自动调用构造函数
EmailValidator validator(email);
if (validator.isValidEmail()) {
cout << "yes" << endl;
} else {
cout << "no" << endl;
}
// validator 对象超出作用域时自动调用析构函数
return 0;
}
#include <iostream>
#include <cstdlib>
using namespace std;
//划分算法
int Partition(int a[],int l,int r) {
int pilot = a[l]; //用序列的第一个记录作为基准
int i = l; int j = r;
while (i!=j) { //从序列的两端交替向中间扫描,直到i=j为止
while (j>i&&a[j]>= pilot) {
j--; //从右向左扫描,找第一个关键字小于pilot的a[j]
}
a[i] = a[j]; //将a[j]前移到a[i]的位置
while (i<j&&a[i] <= pilot) {
i++; //从左向右扫描,找第一个关键字大于pilot的a[i]
}
a[j] = a[i]; ////将a[i]后移到a[j]的位置
}
a[i] = pilot;
return i;
}
//快速排序
void QuickSort(int a[], int l, int r) { //对a[l,r]元素序列进行递增排序
if (l<r) { //序列中至少存在两个元素的情况
int i = Partition(a, l, r);
QuickSort(a,l,i-1); //对左子序列递归排序
QuickSort(a,i+1,r); //对右子序列递归排序
}
}
//输出数组
void display(int a[],int n) {
for (int i = 0; i < n;i++) {
cout << a[i]<<" ";
}
cout << endl;
}
int main() {
int n = 0;
cout << "请输入一个数组的元素个数" << endl;
cin >> n;
int *a = new int[n];
for (int i = 0; i < n;i++) {
cin >> a[i];
}
cout << "输出没排好序的数组元素";
display(a, n);
QuickSort(a,0,n-1);
cout << "输出排好序的数组元素";
display(a, n);
system("pause");
}