Monday, 2 February 2015

Get the maximum occurrence of the character in the string with example in C/C++


Get the maximum occurrence of the character in the string with example in C/Cpp:

Here Input string = “test string for testing”

Constructing the character count array from the input string.

  iCount['e'] = 2
  iCount['s'] = 3
  iCount['t'] = 5
  iCount['r'] = 2
  iCount['i'] = 2
  iCount['f'] = 1
  iCount['o'] = 1
  iCount['f'] = 1
  iCount['n'] = 2
  iCount['g'] = 1

In the above array we can get the maximum number is ‘5’ that is ‘t’

#include "stdafx.h"
#include <stdio.h> #include <stdlib.h> #define TOTAL_CHAR 256

   This function is used to get the count of the array
int *GetCntArry (char *); 

   This function is used to get the maximum index
char GetMaxInd (int *, int); &nbsp

 This function returns the maximum occurring
  character in  the input string
char GetMaxChar (char *pchStr)

{
  int *iCount = GetCntArry (pchStr);
  return GetMaxInd (iCount, TOTAL_CHAR);
}

This function returns an array of size 256 containg iCount of characters in the passed char array

int *GetCntArry (char *pchStr)
{
     int *count = (int *)calloc(TOTAL_CHAR, sizeof(int));
     int i;
     for (i = 0; *( pchStr +i); i++)
      count[*(pchStr +i)]++;
     int iindex = 0,max=0;
     for (i = 0; *( pchStr +i); i++)
      if (count[*(pchStr +i)] > max)
    max= count[*(pchStr +i)], iindex = i;
    /* free memory allocated to count */
    free(count);
    count = NULL;
    return *( pchStr + index);
}
char GetMaxInd (int iArr[], int iSize)
{ 
  int iInd;   int iMaxIndex = 0;   
  for (iInd = 1; iInd < iSize; iInd++)   
    if (iArr[iInd] > iArr[iMaxIndex])     
      iMaxIndex = iInd;   
  /* free memory allocated to iCount */ 
  free (iArr);    iArr = NULL;
  return iMaxIndex;
}

Calling the function and testing it from the main function.

int main ()
{
  char pchStr[] = "this is the sample string";
  printf ("%c", GetMaxChar (pchStr));
  getchar ();
  return 0;
}

No comments: