Q: Write code to calculate character frequencies in a string
Anonymous
If the objective were to return the number of instances of a specific char, this simple solution would seem to work; // Frequency of any given char is in a string int SpecificCharInString(TCHAR tszToken, LPCTSTR lptszString) { int nCounter = 0; for (; *lptszString; *lptszString++) { if (*lptszString == tszToken) { ++nCounter; } } return nCounter; } If the objective is to return a histogram of all discovered chars... I'd do something a bit more like this: // Frequency of any char in a string // Return 1 on Success, -1 on Failure! // Assumes lower case... if upper, you may want to OR with 0x20 in the "while" or before passing to the function. int CharFreqInString(LPTSTR lptszString, PCHAR_COUNT pCharCount) { int nRetVal = -1; if (pCharCount->dwSize = sizeof(CHAR_COUNT)) { while (*(&pCharCount->a + (*lptszString++ - 'a')) += 1, *lptszString); nRetVal = pCharCount->dwSize; } return nRetVal; }
Check out your Company Bowl for anonymous work chats.