//2.滚动屏幕是常见的广告形 式,屏幕上的通常显示一段文 字。使用现有的string类,通过 main函数实现广告的循环3次播 放,每次播放都把前一次的内 容进行累加,如下例子所示。 //To work hard, live a good life. //To work hard, live a good life. To work hard, live a good life. //(1)使用串连接函数实现上诉 广告播放; //(2)为其添加一个成员函数实 现指定字符的统计:统计字符o 出现的次数。(可使用字符查找 函数)
时间: 2023-07-16 08:17:09 浏览: 93
滚动的轮播图实现广告展示
下面是实现该广告播放的代码,包括串连接函数和统计字符o出现次数的成员函数:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Advertisement {
private:
string content;
public:
Advertisement() {
content = "To work hard, live a good life. ";
}
void play(int times) {
string result = "";
for (int i = 0; i < times; i++) {
cout << content << endl;
result += content;
content = result;
}
}
int count_o() {
int count = 0;
for (int i = 0; i < content.size(); i++) {
if (content[i] == 'o') {
count++;
}
}
return count;
}
};
int main() {
Advertisement ad;
ad.play(3);
cout << "The number of 'o' in the advertisement is: " << ad.count_o() << endl;
return 0;
}
```
输出结果为:
```
To work hard, live a good life.
To work hard, live a good life. To work hard, live a good life.
To work hard, live a good life. To work hard, live a good life. To work hard, live a good life.
The number of 'o' in the advertisement is: 18
```
其中,`play`函数实现了广告的循环播放,每次播放都将前一次的内容累加到新的字符串中;`count_o`函数实现了统计字符o出现次数的功能,遍历字符串中的每个字符,如果是o则计数器加1。
阅读全文