对字符串中的字符进行统计



//借鉴HUAWEI OJ其他同仁想法,利用字符与ASCII码互相转化,直接令下标值等于ASCII,方便计数和记录对应的字符。

#include <iostream>
#include <string>
#include <cctype>

using namespace std;
struct calculate
{
 char a;
 int length;
};
int main()
{
 string str;
// char c[129]={'\0'};
 getline(cin,str);  //读入一行字符
 int len=str.size();
// int hash[128]={0};
// int temp[128]={0};
 calculate p[128];
 for(int i=0; i<128; i++)
 {
  p[i].a = '\0';
  p[i].length = 0;
 }
 int k=0;
 for(int i=0;i<len;i++)
 {
  p[str[i]].a  = str[i];
  p[str[i]].length++;
 }
 calculate* pPointer[128];  //指针数组
 for(int i=0; i<128; i++)  //指针数组初始化为p[i]
  pPointer[i] = p+i;

 for(int i = 0; i<127; i++)
 {
  int k = i;
  for(int j= i+1; j<128; j++)
   if(pPointer[j]->length> pPointer[k]->length)
    k=j;
  if(k != i)
  {
   calculate *temp;
   temp = pPointer[i];
   pPointer[i] = pPointer[k];
   pPointer[k] = temp;
  }
 }
 int z=0;
 while(pPointer[z]->length  != 0)
 {
  if((pPointer[z]->a >='0' && pPointer[z]->a <='9') ||(pPointer[z]->a >='a' && pPointer[z]->a <='z')||(pPointer[z]->a >='A' && pPointer[z]->a <='Z')||(pPointer[z]->a == ' '))
   cout << pPointer[z]->a;
  z++;
 }
// puts(c);
 system("pause");
 return 0;
}

猜你喜欢

转载自blog.csdn.net/zhang_fei_fresh/article/details/49624955