Thread: Character that appears max times in string

  1. #1
    Registered User
    Join Date
    Feb 2003
    Posts
    175

    Character that appears max times in string

    Hello All,

    I have developed code for finding character that appears max times in a string. Wanted to know, any better version of this. If two characters appear same number of times then whichever appaers first is given priority.

    RT


    Code:
    #include<stdio.h>
    
    #define MAX_CHAR	26
    
    unsigned char cFreqTable[MAX_CHAR];
    
    main()
    {
    	unsigned char string[200],cMaxChar=0;
    	unsigned iCurrFreq,iMaxFreq;
    	unsigned char *buf = string;
    
    	iCurrFreq = iMaxFreq = 0;
    	printf("Enter the string\n");
    
    	scanf("%s",buf);
    
    	while (*buf)
    	{
    		// convert to lower case
    		if ( ( (*buf) >= 'A' ) && ( (*buf) <= 'Z' ) )
    			(*buf) = (*buf) + ('a' - 'A') ;
    
    		// Increment frequency table
    		cFreqTable['a'-(*buf)] = cFreqTable['a'-(*buf)] + 1;
    
    		iCurrFreq = cFreqTable['a'-(*buf)];
    
    		if ( iCurrFreq > iMaxFreq )
    		{
    			iMaxFreq = iCurrFreq;
    			cMaxChar = *buf;
    		}
    		buf++;
    	}	
    	printf("Character %c appears for max %d times \n",cMaxChar,iMaxFreq);
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > If two characters appear same number of times then whichever appaers first is given priority.
    So have another array which records the index each time you see a char for the first time
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    A couple points:
    • cFreqTable doesn't need to be global
    • main() should be: int main(void)
    • there needs to be a return 0; at the end of the main function
    • that code will only work in an enviroment that has contigious letters
    • use tolower() from <ctype.h> to convert to lower instead

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Custom String class gives problem with another prog.
    By I BLcK I in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2006, 03:40 AM
  2. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. Game of life
    By JoshR in forum C++ Programming
    Replies: 30
    Last Post: 04-03-2005, 02:17 PM
  5. UNICODE and GET_STATE
    By Registered in forum C++ Programming
    Replies: 1
    Last Post: 07-15-2002, 03:23 PM