题目为:统计字符串中不同字符出现的个数,并降序输出
#include <iostream>
#include <cstring>
using namespace std;
void frequency(char *s)
{
int a[100] = {0}, i, j = 0, m = 0, t = 0, b[100] = {0};
if (s[0] == '\0')
{
cout<<"该字符串为空."<<endl;
}
else
{
for (i = 0; i < strlen(s); i++)
{
for (j = 65; j <= 90; j++)
{
if (s[i] == j || s[i] == j + 32)
{
a[j]++;
}
}
}
for (i = 1; i <= strlen(s); i++)
{
m = 0;
t = 0;
for (j = 65; j <= 90; j++)
{
if (a[j] > m)
{
m = a[j];
t = j;
}
}
b[t] = i;
}
for (i = 1; i <= strlen(s); i++)
{
for (j = 65; j <= 90; j++)
{
if (b[j] == i)
cout<<char(j)<<":"<<i<<" ";
}
}
}
cout<<endl;
}
int main()
{
char a[] = "I love China!";
frequency(a);
return 0;
}
要是用C++的话,应该多用点现代写法,手写太麻烦而且容易出错
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void frequency(const string& s)
{
if (s.empty())
{
cout<<"该字符串为空."<<endl;
}
else
{
vector<pair<char,int>> v;
for(char ch:s)
{
auto iter=std::find_if(v.begin(),v.end(),[ch](const pair<char,int>& p){return p.first==ch;});
if(iter!=v.end())
++iter->second;
else
v.push_back({ch,1});
}
sort(v.begin(),v.end(),[](const pair<char,int>& a,const pair<char,int>& b){return a.second>b.second;});
for(const pair<char,int>& p:v)
{
cout<<p.first<<":"<<p.second<<endl;
}
}
}
int main()
{
char a[] = "I hate dxp!";
frequency(a);
return 0;
}
t变量记录频率最高的字母,每找到一个,t值会被更新,最后一个被记录后就只显示长度,引用一个额外的数组来处理
#include <iostream>
#include <cstring>
using namespace std;
void frequency(char *s)
{
int a[100] = {0}, i, j = 0, m = 0, t = 0, b[100] = {0};
if (s[0] == '\0')
{
cout << "该字符串为空." << endl;
}
else
{
for (i = 0; i < strlen(s); i++)
{
for (j = 65; j <= 90; j++)
{
if (s[i] == j || s[i] == j + 32)
{
a[j]++;
}
}
}
for (i = 1; i <= strlen(s); i++)
{
m = 0;
t = 0;
for (j = 65; j <= 90; j++)
{
if (a[j] > m && b[j] == 0)
{
m = a[j];
t = j;
}
}
b[t] = 1; // 标记该字母已被处理
cout << char(t) << ":" << m << " ";
}
}
cout << endl;
}
int main()
{
char a[] = "I love China!";
frequency(a);
return 0;
}
【以下回答由 GPT 生成】
问题分析:
根据问题描述,目前的代码只能输出字符串的长度,而没有实现统计字符串中不同字符出现的个数并按照字符出现次数降序输出的功能。可能存在以下问题或错误:
解决方案:
针对以上问题,可以进行如下优化:
下面是优化后的代码示例(以C++为例):
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include <algorithm>
bool compare(const std::pair<char, int>& a, const std::pair<char, int>& b) {
return a.second > b.second; // 按照值降序排序
}
void countAndSortChars(const std::string& str) {
std::unordered_map<char, int> charCount;
// 统计字符出现次数
for (char c : str) {
charCount[c]++;
}
// 将哈希表中的键值对转换为vector,并按照值降序排序
std::vector<std::pair<char, int>> charCountVec(charCount.begin(), charCount.end());
std::sort(charCountVec.begin(), charCountVec.end(), compare);
// 输出结果
for (const auto& p : charCountVec) {
std::cout << "字符 " << p.first << " 出现次数:" << p.second << std::endl;
}
}
int main() {
std::string str = "abcabcabc";
countAndSortChars(str);
return 0;
}
代码说明:
compare
函数,用于作为排序的比较函数,按照值降序排序。countAndSortChars
函数来实现字符统计和降序排序,并输出结果。main
函数中调用 countAndSortChars
函数进行测试。优化后的代码可以实现统计字符串中不同字符出现的个数,并按照字符出现次数降序输出的功能。
【相关推荐】