<IW****@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
It's to count the number of letters in a string. So I was just going
to go character by character, and it's an a, add one to letters[a], if
it's a b, add one to letters[b], etc. The array just stores integers
If that's the case, I think you've got a misconception regarding characters
in a string and their actual values. The letter 'a' (which differs from the
letter 'A', by the way), already has a value, and giving a value of 1 (or 0)
to the symbol a in an enumeration isn't going to help you do anything,
really.
Suppose you have an array of char containing the string "hello". What you
have, then, are the characters 'h', 'e', 'l', 'l', and 'o' (and possibly a
trailing value of zero, if the it's a c-style null-terminated string).
Let's just look at the first character, 'h'. Its value is determined by the
current character set, which in most cases will be the standard ASCII
character set, and for the letter 'h', that value is 104 (I think...I don't
have the chart handy). So which counter in your array do you want to
increment? Well, if you're only counting letters of the alphabet, then 'h'
is the 8th letter, so you want to increment array[7] (since the first
element is 0).
How do you do that easily, regardless of which letter you're encountering?
Well, if I recall correctly, the letters of the alphabet (at least the
English alphabet) are always given sequential values starting at whatever
'a' is (which is 97 in ASCII, I think). But it might not be 97 on some
system or with some character set. So you don't want to just subtract 97
from your character's value. The easiest way to determine which slot to
increment, then, without having to rely on 'a' being 97, is to subtract
whatever the value of 'a' actually is. But since a character's value can
just be specified by the character itself, you can simply increment the
item: array['h'-'a'].
So...suppose your counts are in an array called counts (wow, what
imagination! :-)), and the input string is in an array called inputstring.
Then, while looping through inputstring (assuming that you use i as your
loop variable), you can do:
counts[inputstring[i]-'a']++;
That gets the value at inputstring[i], subtracts 'a' from it (which is just
some integer value, most likely 97), and increments the item in counts at
that location. In the case of i=1, the letter there is 'h', so it
increments counts[7].
However!!! ...you'll have to do something different if you might have
capital letters, numbers, symbols, etc. I don't know what your requirements
are, whether you might see those, or what you want to do if you do see
those, so I'm not going to advise you on how to handle them (unless you ask
for specific help with those).
Hope this helps...
-Howard