I was doing a coding challenge on codewars.com and the challenge was to take a string as input, check it for duplicate characters and return the number of duplicate characters. It can be assumed that all characters will be letters only.
So anyways I got my code working and submitted it, afterwards I saw this code on the same problem in the number 1 spot, codewars.com lets you see how other people solved the problem too.
Here it is
size_t duplicate_count(const char* text)
{
char seen[127] = { 0 };
size_t duplicates = 0;
char c;
while ((c = *text++))
{
if (seen[tolower(c)]++ == 1) duplicates++;
}
return duplicates;
}
Theres a few things that I don't understand about this code, although I'm sure it's pretty simple.
1) Why use 127 as the size of the seen char array? There are 26 letters in the alphabet, and this person is already casting the characters to lowercase in the while loop, so I wouldn't think you would have to worry about it being uppercase anyways.
2) this line
if (seen[tolower(c)]++ == 1) duplicates++;
I get that it is checking to see if the current character in the string is in the seen array, but how? The syntax isn't making sense to me is what I'm saying.
Thank you all for your time. I was going to post this on code review instead, but I have been told that it's not really a "how to" site.
"AAA"
? – alk Jun 15 '19 at 8:39if
statement before, you should probably read an introduction to C first. – melpomene Jun 15 '19 at 8:39if
statement. Please be specific: What exactly is unclear to you? Do you know what++
does? Do you know how variables work? Function calls? – melpomene Jun 15 '19 at 8:45