patterncppMinor
Finding the most frequent character in a string
Viewed 0 times
thecharacterfindingstringfrequentmost
Problem
This is in C/C++ (using a c-string as input). I'm curious if my solution could be more efficient than it currently is.
char mostFrequent(char *bytes, int length) {
char holder[26];
for (int i = 0; i count) {
count = holder[i];
b = i+97;
}
}
return b;
}Solution
If you are intended to measure the frequency of bytes, as the name of your input string seems to suggest, rather than just lowercase ASCII letters, then your
This also saves you from all the additions and subtractions of the 'magic' number 97. (Seriously, you could have used 'a'.)
Also, your
holder array should be 256 elements long. This also saves you from all the additions and subtractions of the 'magic' number 97. (Seriously, you could have used 'a'.)
Also, your
holder array should consist of ints not chars, because if a certain byte appears more than 256 times in your input string the char will wrap around to zero. Also an array of ints will probably perform more efficiently due to memory alignment.Context
StackExchange Code Review Q#7552, answer score: 7
Revisions (0)
No revisions yet.