#String character counter

30 messages · Page 1 of 1 (latest)

small rose
#

Hello, I need help with making a code that will output a character that is most repeating in string given as input. In case of having multiple of those, then output character with the lowest ASCII code.

I dont know the concept behind the repeating characters except in the case of making a double for loop that would be a counter for a certain character i input previously.

indigo valeBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

olive cloak
#

You could make an array of counters int counters[256]; (one for every possible character)

#

Or std::map<char, int> (in C++, didn't notice this was C)

cosmic sedge
#

a hashmap for this problem is an overkill

#

also this is c not c++

olive cloak
cosmic sedge
#

oh ok i don't really know c++ :v

#

oh map is literally what it says... A map

olive cloak
small rose
#

sorry for the non english ooga language

small rose
olive cloak
#

Mkay?

small rose
#

so how to do it?

#

i think i know how to do ascii code part

olive cloak
#

Create the array of counters (e.g. int counters[256];)

cosmic sedge
#

you can use macro in scanf directly

olive cloak
#

You can use a char as an index for an array. char ch = ...;, counters[ch]++

#

(Though it should probably be counters[(unsigned char)]++;, because otherwise characters can be negative, and you'll go out of bounds. But you don't have to think about this right now)

ebon scroll
#

You will need to initialise this array too.

char s[MAKS_DUZINA_NISKE] = {0};

Making this an array of chars will problably work, as it is unlikely that any string you enter has any character repeating itself 127 times.
Still, for clarity and correctness, I would make this an integer array instead.
For bonus points, you could even make it an unsigned int array seeing as the count will never be negative.

small rose
small rose
#

max array len is already defined. I dont understand what format array is supposed to be and that sprintf function?

#

max array len -1 i do understand as it wants all elements except the null terminator

main skiff
ebon scroll
ebon scroll
# small rose its in the main function and i am not allowed to change the main function

i am not allowed to change the main function

In that case may I also suggest that - admirable as it is - you do not look at the main() function right now and concentrate on implementing function most_used_char().
At least for now.

It's always good to be inquisitive, but perhaps after you completed your task. Because that's where you earn your grade.

small rose
#

But strings and arrays are by far the hardest data types Ive come across