统计字符数组中各类字符的次数,并输出

对于给定的字符数组 char str[100] = {"109238475629020349ejlqjwlrqusfwkjrop345678<>jlsjf029384756"};
(1)统计阿拉伯数字数字0-9出现的次数。
(2)并对数字出现的次数进行降序排序。
(3)对各个数字按照降序序列输出数字及出现次数。

#define _CRT_SECURE_NO_WARNINGS //这一句必须放在第一行
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

/*
对于给定的字符数组 char str[100] = { "109238475629020349ejlqjwlrqusfwkjrop345678<>jlsjf029384756" };
(1)统计阿拉伯数字数字0 - 9出现的次数。
(2)并对数字出现的次数进行降序排序。
(3)对各个数字按照降序序列输出数字及出现次数。
*/
typedef struct Pair//定义一个数对
{
 int n;//数字
 int count;//出现的次数
}Pair;

int Cmp_pair(const void* vp1, const void* vp2)//排序的比较函数
{
 return -(((Pair*)vp1)->count  -  ((Pair*)vp2)->count);
}

int main()
{
 char str[100] = { "109238475629020349ejlqjwlrqusfwkjrop345678<>jlsjf029384756" };
 Pair arr[10];//arr保存0~9的数字和数字出现的次数
 int i;
 int num;
 for (i = 0; i < 10; i++)//初始化arr
 {
  arr[i].n = i;
  arr[i].count = 0;
 }
 for (i = 0; str[i] != '\0'; i++)//遍历str字符串,统计每个数字字符出现的次数
 {
  if (isdigit(str[i]))//是数字字符,需要引用ctype.h
  {
   num = str[i] - '0';//把字符转为数字
   arr[num].count++; //对应的计数器+1
  }
 }

 qsort(arr, 10, sizeof(Pair), Cmp_pair);//快速排序,需要引用stdlib.h

 //按次数从大到小输出
 for (i = 0; i < 10; i++)
 {
  printf("%d出现%d次\n",arr[i].n,arr[i].count);
 }
 
 return 0;
}

C++

#include <iostream>
#include <algorithm>
using namespace std;


bool isdigit(char a){
 if(a == '0' || a == '1' || a == '2' || a == '3' || a == '4' || a == '5' || a == '6' || a == '7' || a == '8' || a == '9')
  return true;
 return false;
}

bool compare(int a,int b)
{
    return a>b;
}


int main(){
 char str[100] = {"109238475629020349ejlqjwlrqusfwkjrop345678<>jls jf029384756"};
 int len = 0;
 for(int i = 0; i < 100; i ++){
  if(str[i] != '\0'){
   len ++;
  }
  else break;
 }
 int count[10] = {};
 for(int i = 0; i < len; i++){
  if(isdigit(str[i])){
   count[str[i] - '0'] += 1;
  }
 }
 // for(int i = 0; i < 10; i ++){
 //  cout << count[i] << " ";
 // }
 // cout << endl;

 sort(count, count+10, compare);
 for(int i = 0; i < 10; i ++){
  cout << i << ":" << count[i] << " ";
 }
 cout << endl;

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值