求字符串中最长的连续出现的字符
时间: 2024-06-16 12:06:13 浏览: 14
要求字符串中最长的连续出现的字符,可以通过遍历字符串的方式来实现。具体步骤如下:
1. 定义一个变量maxCount,用于记录最长连续出现的字符的个数。
2. 定义一个变量currentCount,用于记录当前连续出现的字符的个数。
3. 定义一个变量maxChar,用于记录最长连续出现的字符。
4. 遍历字符串,从第二个字符开始:
- 如果当前字符与前一个字符相同,则currentCount加1。
- 如果当前字符与前一个字符不同,则将currentCount重置为1。
- 如果currentCount大于maxCount,则更新maxCount为currentCount,并将maxChar更新为当前字符。
5. 遍历结束后,maxChar即为最长连续出现的字符。
下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
char findLongestConsecutiveChar(const std::string& str) {
int maxCount = 0;
int currentCount = 1;
char maxChar = str;
for (int i = 1; i < str.length(); i++) {
if (str[i] == str[i - 1]) {
currentCount++;
} else {
currentCount = 1;
}
if (currentCount > maxCount) {
maxCount = currentCount;
maxChar = str[i];
}
}
return maxChar;
}
int main() {
std::string str = "aabbbbccccccddddd";
char longestChar = findLongestConsecutiveChar(str);
std::cout << "The longest consecutive character in the string is: " << longestChar << std::endl;
return 0;
}
```
运行以上代码,输出结果为:
```
The longest consecutive character in the string is: c
```
这里的示例代码中,我们定义了一个函数`findLongestConsecutiveChar`来实现查找最长连续出现的字符的功能。在`main`函数中,我们给定了一个字符串`str`,并调用`findLongestConsecutiveChar`函数来查找最长连续出现的字符,并将结果输出到控制台。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)