找字符串中子串个数

· · 个人记录

// 找子串并计数,ss:子串 
int count(string s, string ss) {
    int cnt = 0;
    int pos = s.find(ss);

    // 找第一个子串 
    if (pos != -1) {
        cnt++;
    } else {
        return cnt;
    }

    // 找后续子串 
    while (pos != -1) {
        pos = s.find(ss, pos + 1);
        if (pos != -1) {
            cnt++;
        } else {
            return cnt;
        }
    }
}