Question:

C Programming <Identifying numbers of characters & digits in a string>?

by  |  earlier

0 LIKES UnLike

The program is to identify the number of alphabet(capital & small), digits(0 to 9) that appears in a string.

I know the source code for it(strlen,switch case, i etc). However, using switch case is a lot of work. Is there an easier way to do it?

Thanks!

The program goes like this:

<Input>

Enter a string : KaccBBZe1344*9)(k

<Output>

a =1, b =0, c =2, d =0, e =1, f=0.....k=1.........z=0

A =0, B =2, C =0...K =1.....Z =1

0 =0, 1 =1, 2 =0, 3=1, 4 =2....9 =0

Others = 3 // *)(

By casting char to int, comparison is unavoidable (if else...). Is there a function that identify the string?

Appreciate if anyone can help. Thank you.

 Tags:

   Report

1 ANSWERS


  1. int *foo(char *str) {

    static int counts[256]; /* inited to zeros for first call, anyway */

    while (*str != &#039;\0&#039;) {

      counts[*str]++;

    }

    return counts;

    }

    I&#039;ve not tested this, or even compiled it.  But i&#039;m indexing into an array of counts for each character by using the character as an index.  Note: no casts.  char is already an integer like type.  So if you want to know how many A&#039;s there where, counts[&#039;A&#039;] is the answer.  There won&#039;t be any counts[0].

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions