定义一个类STR,将键盘输入的一行字符串中连续的数字字符拼接成整数,并将拼接的所有整数之各办出。例如,如果输入的字符串是“12abc34ed345”,则字符串中的数字字符将拼接的3个整数之和为:12+34+345=392。具体要求如下:
(1)类的成员要求定义为一个指针;
(2)构造函数中根据参数传递的字符串的长度申请相应的动态内存,并将参数字符串存入申请的动态内存;
(3)定义析构函数完成必要的操作;
(4)定义一个函数按题意将字符串中提取的整数之和存入相应的成员变量;
(5)定义一个函数输出成员字符串及提取的整数之和;
(5)在主函数中定义一个元素个数不少于40的字符数组,并从键盘输入一行前后端含空格的字符串存入该数组。然后用该字符数组生成一个对象,再通过该对象调用相应的成员函数实现实现题意功能,最后输出改写后的字符串。
#include <iostream>
#include <cstring>
using namespace std;
class STR {
private:
char* str; // 存储输入的字符串
int* nums; // 存储提取出来的整数
int len; // 存储输入字符串的长度
int sum; // 存储提取出来的整数之和
public:
STR(const char* s) {
len = strlen(s);
str = new char[len+1];
strcpy(str, s);
nums = new int[len];
sum = 0;
}
~STR() {
delete[] str;
delete[] nums;
}
void extractIntegers() {
int i = 0, j = 0;
while (i < len) {
if (str[i] >= '0' && str[i] <= '9') {
int num = 0;
while (i < len && str[i] >= '0' && str[i] <= '9') {
num = num * 10 + str[i] - '0';
i++;
}
nums[j++] = num;
sum += num;
} else {
i++;
}
}
}
void print() {
cout << "原始字符串:" << str << endl;
cout << "提取的整数:";
for (int i = 0; i < len; i++) {
if (nums[i] != 0) {
cout << nums[i] << " ";
}
}
cout << endl;
cout << "整数之和:" << sum << endl;
}
};
int main() {
char s[40];
cout << "请输入一个字符串:" << endl;
cin.getline(s, 40);
STR obj(s);
obj.extractIntegers();
obj.print();
return 0;
}
完整str类代码
#include <iostream>
#include <cstring>
using namespace std;
class STR {
private:
char *str; // 存储字符串的指针
int num; // 整数之和
public:
STR(char *s);
~STR();
void findIntegers(); // 查找整数并计算整数之和
void printResult(); // 输出字符串及整数之和
};
STR::STR(char *s) {
// 根据字符串长度申请内存
str = new char[strlen(s) + 1];
strcpy(str, s);
}
STR::~STR() {
delete[] str; // 释放内存
}
void STR::findIntegers() {
num = 0; // 整数之和初始化为0
// 遍历字符串中的每一个字符
for (int i = 0; str[i] != '\0'; i++) {
// 如果当前字符是数字
if (isdigit(str[i])) {
int j = i;
int n = 0;
// 向后查找连续的数字字符
while (isdigit(str[j])) {
n = n * 10 + (str[j] - '0');
j++;
}
// 将拼接的整数加到整数之和中
num += n;
i = j - 1; // 跳过已经拼接的数字字符
}
}
}
void STR::printResult() {
cout << "字符串为:" << str << endl;
cout << "拼接的整数之和为:" << num << endl;
}
int main() {
char s[40];
cout << "请输入一个字符串(长度不超过40):" << endl;
cin.getline(s, 40);
STR str(s); // 创建STR对象
str.findIntegers(); // 查找整数并计算整数之和
str.printResult(); // 输出字符串及整数之和
return 0;
}