字符串出现次数统计

基本要求:

找出一个字符串中查找第一个只出现一次的字符。
找出字符串中出现次数最多的字符,并统计最大次数。

#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;
}

这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值