If your code is confusing you then it is wrong. I recommend you start over.
The "most common character" is the one that appears more than any other character. The only way you can know that is by counting it.
The thing you use to count the number of times things appear is called a
histogram. A histogram is simply a list of things and the number of times they appear.
For example, in:
"Hello everyone!"
We get the following histogram:
' ' 1
'!' 1
'H' 1
'e' 4
'l' 2
'n' 1
'o' 2
'r' 1
'v' 1
'y' 1
The largest count is 4, so 'e' is the most common character in the given string.
You can also see that there may be ties -- there might not be only one most common character.
The hard part is actually maintaining a histogram for any random data. For a character, you could easily use an array of 128 elements (one for each character), all initialized to zero. Then the character itself is an index into the histogram.
1 2 3 4 5 6
|
int histogram[ 128 ] = { 0 };
for each char c in string s
{
histogram[c] += 1;
}
|
Another way to do it is to simply
sort your string. For example, our string above sorts to:
" !Heeeellnoorvy"
We can see that the longest substring of equal values is 'e' -- there are four in a row. Finding the longest substring is very much like your 'find the minimum or maximum of an array' homework. You might find this method a little more difficult than the simple array histogram, so I recommend you use the first method, but I present it here so that you can see that there is more than one way to do it.
Hope this helps.