给定一个长度不限的字符串,请找出该字符串中出现次数最多的那个字符,并打印出该字符及出现次数(C/C++版)

#include<iostream>
using namespace std;
/**
 * @brief findchar  给定一个长度不限的字符串,请找出该字符串中出现次数最多的那个字符,并打印出该字符及出现次数;
    如果多个字符的出现次数相同,只打印首个字符;输出字符的大小写格式要与输入保持一致,大小写不敏感模式下,输出字符的大小写格式与该字符首次出现时
    的大小写格式一致。实现时无需考虑非法输入。
 * @param [in] st  输入的字符串
 * @param [out] ch  出现次数最多的字符
 * @param [out] cnt 出现次数最多的字符数
 * @param [in] sensitive  是否大小写敏感
 * @return 是否获取成功
 */
bool findchar(const string& st,  char* ch,  int* cnt, bool issensitive=true){
     bool ret = true;
     int  table[52] = {0};
     int  max = 0, maxindex =0, index = -1;

     if(st.length() <= 0)
         return false;
     string str = st;

     for(unsigned int i=0; i<str.length(); i++) {
         if((str.at(i) <= 'Z') && (str.at(i) >= 'A') ) {
             index = static_cast<int>( str.at(i) - 'A');
             table[index]++;
         }
         else if((str.at(i) <= 'z') && (str.at(i) >= 'a')){
             index = static_cast<int>(str.at(i) - 'a') ;
             index += 26;
             table[index]++;
         }
     }

     if(issensitive) {
         for(int i=0; i<52;i++)  {
             if(max < table[i]){
                 max = table[i];
                 maxindex = i;
             }
         }
     }
     else{
         for(int i=0; i<26;i++)  {
             table[i] = table[i] + table[i+26];
             table[i+26] = 0;
         }
         for(int j=0; j<26; j++) {
             if(max < table[j]) {
                 max = table[j];
             }
         }

         for(unsigned int i=0; i<str.length();i++) {
             int cnt = -1;
             (str.at(i) > 'Z') ? (cnt = static_cast<int>(str.at(i) - 'a')) : \
                                 ( cnt = static_cast<int>(str.at(i) - 'A') );
             
             if(table[cnt] == max){
                 (str.at(i) > 'Z') ? (maxindex = 26 + cnt ) : (maxindex = cnt);
                 break;
             }
         }
     }

    if((maxindex < 26) && (max>1)  ) {
         *ch = maxindex + 'A';
         *cnt = max;
    }
    else if((maxindex >= 26) && (max>1) ) {
        *ch = maxindex + 'a' - 26;
        *cnt = max;
    }
    else if(max==1){
        *ch = str.at(0);
        *cnt = max;
    }
    return ret;
}

int main()
{
    char ch = 0;
    int cnt = 0;
    string str = "SssssMaammmmmmmaAde";
    if(findchar(str, &ch, &cnt, false))
        cout << "ch: " << ch << " cnt: " << cnt << endl;
    else
        cout << "failed" << endl;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值