字符串出现次数统计
程序员文章站
2022-03-08 14:05:33
...
基本要求:
找出一个字符串中查找第一个只出现一次的字符。
找出字符串中出现次数最多的字符,并统计最大次数。
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<iostream>
using namespace std;
int findmaxcount(const char *str,int *pcount,char *m,char *one)
{
unsigned int arr[256] = { 0 };
const char *tmp = str;
int max = 0;
assert(str);
assert(m);
assert(one);
while (*tmp)
{
arr[*tmp]++;
tmp++;
}
tmp = str;
for (int i = 0; i < 255; i++)
{
if (arr[i] == 1)
{
*one = i;
}
if (max < arr[i])
{
max = arr[i];
*pcount = max;
*m = i;
}
}
return 0;
}
int main()
{
char *pa = "aaaabffaaggcxcwaabdww";
int count;
char maxchar;
char retone;
findmaxcount(pa,&count,&maxchar,&retone);
cout <<"最大次数为"<< maxchar<<"出现了"<<count<<"次" << endl;
cout << "一次字符" << retone << endl;
system("pause");
return 0;
}
扩展:找出一个字符串中出现次数第二多的字符。
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string>
#include<iostream>
using namespace std;
int findmaxcount(const char *str,int *pcount1,char *m1, int *pcount2,char *m2,char *one)
{
unsigned int arr[256] = { 0 };
const char *tmp = str;
int first = 0;
int second = 0;
int flagone = 0;
char fi='0';
char se='0';
assert(str);
assert(m1);
assert(m2);
assert(one);
while (*tmp)
{
arr[*tmp]++;
tmp++;
}
tmp = str;
for (int i = 0; i < 255; i++)
{
if (arr[i] == 1)
{
*one = i;
flagone = 1;
}
if (first < arr[i])
{
second = first;
first = arr[i];
se = fi;
fi = i;
*m1 = fi;
*m2 = se;
*pcount1 = first;
*pcount2 = second;
}
else if (second < arr[i])
{
second = arr[i];
se = i;
*m2 = se;
*pcount2 = second;
}
}
if (flagone == 0)
{
cout << "没有一次字符" << endl;
}
return 0;
}
int main()
{
char *pa = "aaaabbffaaqggggww";
int firstcount,secondcount;
char firstchar;
char secondchar;
char retone;
findmaxcount(pa,&firstcount,&firstchar,&secondcount,&secondchar,&retone);
cout <<"最大次数为"<< firstchar <<"出现了"<< firstcount <<"次" << endl;
cout << "第二大次数为" << secondchar << "出现了" << secondcount << "次" << endl;
cout << "一次字符" << retone << endl;
system("pause");
return 0;
}
上一篇: JS之div模块截图并下载功能实现