Find the first occurrence of the most frequently occurring character in a string

Source: Internet
Author: User

    • Find the first occurrence of the most frequently occurring character in a string

Detailed Description:

    • Interface description

Prototype:

BOOL Findchar (Char* pinputstring, char* pChar) ;

Input parameters:

char* pinputstring : String

Output parameters (the memory area pointed to by the pointer is guaranteed to be valid):

char* PChar : The most frequently occurring characters

return value:

false exception failed

true output succeeded


#include <iostream> #include <string.h>using namespace Std;bool findchar (char* pinputstring, char* PChar) {/ /here to implement the function if (pinputstring==null) return false;int  count[256]={0};int  max=count[0];int  t;while (* pinputstring!= ' + ') {count[*pinputstring]++;p inputstring++;} for (int i = 0; i < ++i) {if (Max < count[i]) {max = count[i];t=i;}} *pchar=char (t); return true;} int main () {char str[20]= "ddddddddaaaaaaaa"; char C;cout<<findchar (STR,&C);    }
program output A, obviously the first is D, the problem is where, we traverse the string is the first occurrence of ASCII code small characters, so the above procedures need to be improved.

Correct code:

BOOL Findchar (char* pinputstring, char* pChar) {int thiscnt = 0;int maxcnt = 0;//implements the function here if (pinputstring = = NULL | |  *pinputstring = = ' + ') return False;*pchar=pinputstring[0];int Len=strlen (pinputstring), if (len==1) return true;else{ for (int i=0;i<len;i++) {thiscnt=0;for (int j=0;j<len;j++) {if (pinputstring[i]==pinputstring[j]) thiscnt++;} if (thiscnt>maxcnt) {maxcnt=thiscnt;*pchar=pinputstring[i];}} return true;}}




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Find the first occurrence of the most frequently occurring character in a string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.