• C

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

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();
}
gothic130Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

n_fortynineCommented:
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
gothic130Author Commented:
Could you explain it deeply? I don't get quite right :( (I'm a begginer)
0
n_fortynineCommented:
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
The Five Tenets of the Most Secure Backup

Data loss can hit a business in any number of ways. In reality, companies should expect to lose data at some point. The challenge is having a plan to recover from such an event.

jkrCommented:
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
n_fortynineCommented:
>>  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
Kent OlsenDBACommented:

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

And the whole homework done :o)
0
gothic130Author Commented:
WOW but Kent, the code you wrote can be done without using stdlib.h ???
0
gothic130Author Commented:
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
n_fortynineCommented:
>>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
dennis_georgeCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dennis_georgeCommented:
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
Sys_ProgCommented:
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
AjarCommented:
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
gothic130Author Commented:
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
Sys_ProgCommented:
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
gothic130Author Commented:
>>caCount[256] ={0};

Is there any otherway to initialize the array?
0
Kent OlsenDBACommented:

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
gothic130Author Commented:
Thanks to all of you.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.