Skip to main content
gamedev.net
🔒 Locked

algorithm

Started by popcorn 2 replies 200+ views
Original Post
popcorn
popcorn
I am wondering if anyone could give me the algorthm for cunting the number of times a character appears on a string. eg. if i type in the string "hello" then the output would be h appears 1 time e appears 1 time l appears 2 time o appears 1 time
How about them apples?
Crispy
Crispy

    
//don't know the precise character codes by heart... or the difference between a and A. You'll need to edit the code if you want it to handle capital and small letters both correctly since afaik they're not subsequent...

int alphabet[NUM_CHARCTERS_IN_ALPHABET];

for(unsigned i = 0; i < strlen(str); i++)
{
alphabet[str[i] - 'a']++;
}

char buf[25];

for(unsigned i = 0; i < NUM_CHARCTERS_IN_ALPHABET; i++)
{
if(alphabet[i])
{
sprintf(buf, " appears %i times\0", alphabet[i]);
buf[0] = i + 'a';
cout << buf << endl;
}
}


untested

Crispy

edit: typo


[edited by - crispy on June 16, 2002 6:09:03 PM]
"Literally, it means that Bob is everything you can think of, but not dead; i.e., Bob is a purple-spotted, yellow-striped bumblebee/dragon/pterodactyl hybrid with a voracious addiction to Twix candy bars, but not dead."- kSquared
Thunder_Hawk
Thunder_Hawk
<LOL>...member since...what''s that?...today?...no, that''d make it too obvious...</LOL>

_____________________________

And the Phoenix shall rise from the ashes...

--Thunder_Hawk -- ¦þ
______________________________
______________________________________________________________________________________The Phoenix shall arise from the ashes... ThunderHawk -- ¦þ"So. Any n00bs need some pointers? I have a std::vector<n00b*> right here..." - ZahlmanMySite | Forum FAQ | File Forma

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.