Solved

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

Posted on 2003-10-28
19
304 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
  • 2
  • +4
19 Comments
 
LVL 4

Expert Comment

by:n_fortynine
ID: 9636481
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
ID: 9636531
Could you explain it deeply? I don't get quite right :( (I'm a begginer)
0
 
LVL 4

Expert Comment

by:n_fortynine
ID: 9636581
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Assisted Solution

by:jkr
jkr earned 50 total points
ID: 9636599
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
ID: 9636602
>>  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:Kent Olsen
Kent Olsen earned 100 total points
ID: 9637421

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
ID: 9638871
>>Short, sweet, and simple.

And the whole homework done :o)
0
 

Author Comment

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

Author Comment

by:gothic130
ID: 9639155
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
 
LVL 4

Expert Comment

by:n_fortynine
ID: 9639185
>>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
ID: 9639352
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
ID: 9639361
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
ID: 9639440
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
ID: 9639606
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
ID: 9639642
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
ID: 9639737
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
ID: 9642966
>>caCount[256] ={0};

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

Expert Comment

by:Kent Olsen
ID: 9645494

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
ID: 9645721
Thanks to all of you.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.

728 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