对于给定的字符数组 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;
}