滚动屏幕是常见的广告形式,屏幕上的通常显示一段文字。使用现有的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-11-22 21:54:07 浏览: 31
以下是使用串连接函数实现广告播放的代码:
```c++
#include <iostream>
#include <string>
using namespace std;
class Advertisement {
private:
string content; // 广告内容
public:
Advertisement(string ad) {
content = ad;
}
void play(int times) {
string fullContent = content;
for (int i = 1; i < times; i++) {
fullContent += content;
}
cout << fullContent << endl;
}
};
int main() {
Advertisement ad("To work hard, live a good life. ");
ad.play(3);
return 0;
}
```
输出结果为:
```
To work hard, live a good life. To work hard, live a good life. To work hard, live a good life.
```
以下是添加了统计字符o出现次数的代码:
```c++
#include <iostream>
#include <string>
using namespace std;
class Advertisement {
private:
string content; // 广告内容
public:
Advertisement(string ad) {
content = ad;
}
void play(int times) {
string fullContent = content;
for (int i = 1; i < times; i++) {
fullContent += content;
}
cout << fullContent << endl;
}
int countChar(char c) {
int count = 0;
for (int i = 0; i < content.length(); i++) {
if (content[i] == c) {
count++;
}
}
return count;
}
};
int main() {
Advertisement ad("To work hard, live a good life. ");
ad.play(3);
cout << "Number of 'o': " << ad.countChar('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.
Number of 'o': 6
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)