c++编写一个函数,接受一个字符串作为参数,计算该字符串中每个字符出现的次数,并将结果存储在一个数组中返回。
时间: 2024-12-29 14:32:57 浏览: 70
在 C++ 中,你可以创建一个名为 `countCharacters` 的函数,它接收一个 `std::string` 类型的参数,并通过遍历整个字符串来统计每个字符出现的次数。然后将结果存储在一个整数数组中并返回。这里是一个简单的实现示例:
```cpp
#include <iostream>
#include <unordered_map>
#include <vector>
// 函数声明
std::vector<int> countCharacters(const std::string& input);
// 函数主体
std::vector<int> countCharacters(const std::string& input) {
std::vector<int> charCounts(256); // 初始化一个大小为ASCII码范围的向量
for (char c : input) {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') { // 只统计字母
charCounts[c]++;
}
}
return charCounts; // 返回包含字符计数的结果向量
}
int main() {
std::string str = "Hello, World!";
std::vector<int> counts = countCharacters(str);
// 输出结果
for (size_t i = 0; i < counts.size(); ++i) {
if (counts[i] > 0) {
std::cout << "Character '" << static_cast<char>(i) << "' appears " << counts[i] << " times.\n";
}
}
return 0;
}
```
在这个例子中,我们假设输入字符串仅包含英文字符。函数 `countCharacters` 使用了一个 `std::unordered_map` 或者 `std::vector` 来记录每个字符及其对应的出现次数,但这里为了简化示例,我们仅考虑 ASCII 字符范围,并且只处理大写字母和小写字母。
阅读全文