Zachary Schwatz Zachary Schwatz - 11 months ago 111
C++ Question

Why is the return value always 0 on this function?

Wrote this function which takes two strings and outputs number of common characters. Can't get it to work with online compiler... Seems logically fine to me.

int commonCharacterCount(std::string s1, std::string s2) {
int stringCount1[26]{ 0 };
int stringCount2[26]{ 0 };
int charGet;
int total{ 0 };

for (auto i = 0; i < s1.length(); i++)
{
charGet = s1[i];
stringCount1[charGet - 97] = stringCount1[charGet - 97]++;
}
for (auto i = 0; i < s2.length(); i++)
{
charGet = s2[i];
stringCount2[charGet - 97] = stringCount2[charGet - 97]++;
}
for (auto i = 0; i < 26; i++)
{
total = total + min(stringCount1[i], stringCount2[i]);
}

return total;
}

Answer Source

x++ return x's initial value

so

stringCount1[charGet - 97] = stringCount1[charGet - 97]++; returns stringCount1[charGet - 97]'s initial value, means 0. or might be undefined depending on your compiler version, in my case it just happened to return the initial value.


Just use stringCount1[charGet - 97]++ or stringCount1[charGet - 97] = stringCount1[charGet - 97] + 1 instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download