ios中字符串中包含某個字符串的個數(shù)

//循環(huán)方法
///核心思想是找到相同字符串就對字符串進(jìn)行截取,然后對剩余字符串進(jìn)行

  • (NSInteger)getCountFrom:(NSString)allStr with:(NSString)cutStr{
    //空的時候直接返回0
    if (allStr.length == 0) {
    return 0;
    }
    //接下來是處理字符串
    NSString *leftStr = allStr;
    NSInteger includeCount = 0;
    //顯得我嚴(yán)謹(jǐn),其實(shí)這里循環(huán)條件無所謂
    while (leftStr.length >= cutStr.length) {
    NSRange range = [leftStr rangeOfString:cutStr];
    if (range.location != NSNotFound) {
    includeCount += 1;
    leftStr = [leftStr substringFromIndex:range.location + range.length];
    }else{
    return includeCount;
    }
    }
    return includeCount;
    }

//遞歸方法
///核心思想是找到相同字符串就對字符串進(jìn)行截取,然后對剩余字符串進(jìn)行

  • (NSInteger)getCountFrom1:(NSString)allStr with:(NSString)cutStr{
    static NSInteger includeCount = 0;
    //直接處理字符串
    if (allStr.length < cutStr.length) {
    return includeCount;
    }
    NSRange range = [allStr rangeOfString:cutStr];
    if (range.location != NSNotFound) {
    includeCount += 1;
    [self getCountFrom1:[allStr substringFromIndex:range.location + range.length] with:cutStr];
    }else{
    return includeCount;
    }
    return includeCount;
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容