33,007
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
int main()
{
// 统计ASCII字符出现次数
int count[257 = {0};
char ch;
//从键盘不断输入,直到回车
while ( (ch = getchar()) != '\n')
{
count[ch - 0]++;
}
for (int i = 0; i < 257; i++)
{
if( count[i] )
cout < < (char)i < < ":" < < count[i] < < endl;
}
return 0;
}
#include <stdio.h>
int _tmain(int argc, _TCHAR* argv[])
{
//charNum[0]~charNum[255]分别对应ASCII码中各字符出现的次数 在输入字符串之前都是0
int charNum[256] = {0};
char *str = "babshasgfsfdjkfghfkldhh234gkrthggh4y682378462tej";
char *c = str;
while(*(c++))charNum[*c]++;//*c做下标是亮点 这样可以快速定位 绝对比链表快
//打印结果
for(int i = 0; i<256; i++)if(0!=charNum[i])printf("%c %d\n", i, charNum[i]);
return 0;
}
typedef std::map<char,int> CharMap;
CharMap g_map;
void Countchar(char ch)
{
CharMap::iterator iter= g_map.find(ch);
if(iter==g_map.end())
g_map[ch]=1;
else
iter->second+=1;
}
void OutCount()
{
CharMap::iterator iterbeg= g_map.begin();
CharMap::iterator iterend= g_map.end();
CharMap::iterator iter= g_map.begin();
for(iter=iterbeg;iter!=iterend;iter++)
{
TRACE("字符%c出现%d次\r\n",iter->first,iter->second);
}
}
void Test()
{
char *ptest="1111111aaadddddddddffff";
int len=strlen(ptest);
for(int i=0;i<len;i++)
{
//遍历统计每个字符
Countchar(ptest[i]);
}
//输出统计结果
OutCount();
}