开发者

How to count string occurence in string in C++ [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help 开发者_如何学JAVAclarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

Example I have inputted "he he she she she " output " he 2 she 3 "


You could use a std::map. Since the value of a non-existing key is inserted implicitly with the default value (0 for unsigned) when calling the []-operator, you could tokenize the string and then do the following:

++map[token];

Afterwards you have a map of strings and each entry has a pair of a string (which is a token you parsed before) and an unsigned int indicating how often the token occurred.


This is what I writed from memory without testing. It should return number of all words withing your string. This is not doing exacly what you need. But you need to think by yourself a little bit. It is easy to implement some kind of collection that would hold your own structs (string + number of occurenced).

INT GetStringsNumber(char *szInput)
{
    INT iReturn = 0;
    INT iSize = strlen(szInput) - 1;
    for(INT i = 0; i <= iSize; i++)
    {
        if(szInput[i] == ' ')
        {
            if(i < iSize && szInput[i+1] != ' ')
            {
                iReturn++;
            }
        }
    }
    return iReturn;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜