Solved

How many times a letter is in a string...

Posted on 2003-10-28
19
291 Views
Last Modified: 2010-04-15
I'm doing a program to know how many times a letter is in a string. Any idea??? :) Thanks!
I got this but  I think I'm lost:

#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
 char *string;
 int long, n;
 clrscr();
 gets(&string[0]);
 long=strlen(string);
 for(n=long; n>=0; n--)
 {
   printf("%s\n",string);
 }
 getch();
}
0
Comment
Question by:gothic130
  • 6
  • 4
  • 2
  • +4
19 Comments
 
LVL 4

Expert Comment

by:n_fortynine
Comment Utility
I doubt that you can name your variable "long" since it's a reserved keyword for the type with that same name.
What you should do is basically traverse the string (you can use the loop there) and use an int counter to denote how many times you've run into the desired letter. Start out at 0 and increment this counter each time you see it. Works for you?
0
 

Author Comment

by:gothic130
Comment Utility
Could you explain it deeply? I don't get quite right :( (I'm a begginer)
0
 
LVL 4

Expert Comment

by:n_fortynine
Comment Utility
I missed the part that you cannot call your string "string" for the same reason I said.
Well, since you have found the length of you string, you can use the for loop you have written there, except that instead of  printf("%s\n",string); you do:
loop from the last index to the first index (be careful with these indexes)
  compare the i-th element of the string to the desired letter, if they're equal you add 1 to the value of the counter.
Simple as that :)
0
 
LVL 86

Assisted Solution

by:jkr
jkr earned 50 total points
Comment Utility
Well, the idea is to use a char array:

char string [ 1024];

and check each element if it matches:

char c = 'a';

if ( c == string[n]) {

   // letter at pos. 'n' matches 'a'
}
0
 
LVL 4

Expert Comment

by:n_fortynine
Comment Utility
>>  compare the i-th element of the string to the desired letter, if they're equal you add 1 to the value of the counter.
This part is what should be in place of printf(...) I hope I didn't confuse you.
0
 
LVL 45

Assisted Solution

by:Kdo
Kdo earned 100 total points
Comment Utility

Hi gothic130,

There are several good ideas here so far...  Allow me to suggest a couple more, using your original program.

First, *string isn't appropriate for a buffer.  *string is a pointer to a character, not a buffer, so the call to gets() will result in the string being stored someplace you probably don't want it -- like on top of something critical.


Second, counting all of every character takes no more time than counting all of one character.  (That reads funny, but the theory holds up.)  Instead of the traditional:

if (string[index] == TargetCharacter)
  Count++;

You can have an array of counters that count total up the number of times each character occurs.  Then display the number of times the target is found.

for (index = 0; string[index]; index++)
  Count[string[index]]++;

printf (" '%c' occurred %d times\n", Count[TargetCharacter]);


Third, don't use gets().  A very long line can overflow the buffer and scribble on your program.  Use fgets() instead.


So, with these changes, your program looks like this:

#include <stdlib.h>
#include <stdio.h>

char string[1000];
int Count[256];
char TargetChar;

main()
{
  memset (Count, 0, sizeof (Count));
  fprintf (stdout, "Enter the string:  ");
  fgets(string, 1000, stdin);
  fprintf (stdout, "Enter the character:  ");
  TargetChar = getc (stdin);
  for (index = 0; string[index]; index++)
    Count[string[index]]++;

  printf (" '%c' occurred string '%s', %d times\n", string, Count[TargetCharacter]);
 }


Short, sweet, and simple.

Kent

0
 
LVL 86

Expert Comment

by:jkr
Comment Utility
>>Short, sweet, and simple.

And the whole homework done :o)
0
 

Author Comment

by:gothic130
Comment Utility
WOW but Kent, the code you wrote can be done without using stdlib.h ???
0
 

Author Comment

by:gothic130
Comment Utility
Maybe I explained wrong what I want, but I want the program to ask for a string and then it's suppose to give the letters that repeats the most (without specify any letter). i.e. String: hello
Letter l  repeats 2 times.

String: Hello there
Letter e repeats 3 times.
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 4

Expert Comment

by:n_fortynine
Comment Utility
>>Maybe I explained wrong what I want, but I want the program to ask for a string and then it's suppose to give the l>>etters that repeats the most (without specify any letter). i.e. String: hello
>>Letter l  repeats 2 times.

Misunderstood? At least I did :)

>>I'm doing a program to know how many times a letter is in a string
0
 
LVL 5

Accepted Solution

by:
dennis_george earned 250 total points
Comment Utility
Hi,
  I think following is the simplest and straight forward program to get the maximum occurance of any char... in a string

  char caBuffer[256] ;
  int caCount[256] ={0};

  printf("Enter the String :: " );
  gets(caBuffer) ;

  int nLen = strlen(caBuffer) ;

   int nMax = 0, nIndex = 0 ;

   for(int i = 0; i < nLen; i++){
       int num = caCount[ caBuffer[i] ]++ ;

      if( num > nMax ){
                 nMax = num ;
      nIndex = i ;
      }
  }

  printf("\n Letter %c repeats %d times \n",  caBuffer[nIndex] , nMax + 1);


Dennis
0
 
LVL 5

Expert Comment

by:dennis_george
Comment Utility
The above program is case sensitive....
if you want to make it case insensitve then

change int num = caCount[ caBuffer[i] ]++ to

 int num = caCount[ tolower(caBuffer[i]) ]++

 Dennis
0
 
LVL 10

Assisted Solution

by:Sys_Prog
Sys_Prog earned 100 total points
Comment Utility
Heh then that would a continuation of Kent's solution
Only a small addition in Kent's code
Here is the complete code


#include <stdlib.h>
#include <stdio.h>

char string[1000];
int Count[256];

main()
{
  int index ;
  int max = -1 ;
  char TargetChar;
  memset (Count, 0, sizeof (Count));
  fprintf (stdout, "Enter the string:  ");
  fgets(string, 1000, stdin);
  //fprintf (stdout, "Enter the character:  ");
  //TargetChar = getc (stdin);
  for (index = 0; string[index]; index++)
    {
      Count[string[index]]++;
      if ( Count[string[index]] > max )
        {
          max = Count[string[index]] ;
          TargetChar = string[index] ;
        }
    }  
  if ( max == 1 )
    printf ( "None of the characters occur more than once " ) ;
  else  
    printf (" %c occurred in string %s, %d times\n", TargetChar, string, max);
  system ( "PAUSE" ) ;
 }

0
 
LVL 6

Expert Comment

by:Ajar
Comment Utility
THIS program does exactly what you want..

#include <stdio.h>
main()
{
 char string_buf[1024],*temp;
 char character_to_search;
 int  count = 0;
 
// READ THE STRING
fflush(stdin); //flush the std in stream
puts("ENTER THE STRING : ");fgets(string_buf,1024,stdin);
// REad the character to search
puts("ENTER THE STRING : ");scanf("%c",&character_to_search);
//NOW THE STRING IS THERE IN THE string_buffer and
//String is a character array terminated by a null character
//we can search char by char.
temp = string_buf;// point the temp pointer to beginning of the string

while(temp !='\0')/*a string terminates with a  '\0' or null char*/
{
    if(*temp == character_to_search) count ++;
    temp++; // move on to next character
}
//print the output  
printf("THE STRING '%s' has the character '%c'   %d  number of times ",string_buf,character_to_search,count);
}
0
 

Author Comment

by:gothic130
Comment Utility
Dennis, could you explain me why did you put this: {0} in this line: int caCount[256] ={0};  and why the number has to be such big (256)???
0
 
LVL 10

Expert Comment

by:Sys_Prog
Comment Utility
He has initialized the whole array [all array locations] to zero

And regarding 256, its because of the ascii values of the characters u enter

suppose u enter aab

Then the array would be populated as shown below

caCount[97] = 2
caCount[98] = 1

Rest all the locations of the caCount array would contain 0.

This is because the ascii value of a is 97, that of b is 98
0
 

Author Comment

by:gothic130
Comment Utility
>>caCount[256] ={0};

Is there any otherway to initialize the array?
0
 
LVL 45

Expert Comment

by:Kdo
Comment Utility

int caCount[256] =
{
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
};


or within the program, do:

 memset (caCount, 0, sizeof (caCount));



Kent
0
 

Author Comment

by:gothic130
Comment Utility
Thanks to all of you.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now