已知一个字符串,比如asderwsde,寻找其中的一个子字符串比如sde的个数,如果没有返回0,有的话返回子字符串的个数

本文介绍了一个C++程序示例,该程序用于在一个给定的字符串中查找特定子字符串出现的次数。通过遍历主字符串并与子字符串进行比较,程序能够准确地统计出子字符串在主字符串中出现的频率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/* 
    已知一个字符串,比如asderwsde,寻找其中的一个子字符串比如sde的个数,如果没有返回0,有的话返回子字符串的个数。 
//*/  
  
#include <iostream>   
#include <iomanip>   
#include <limits>   
  
using namespace std;  
bool matchsub(char* pchar, char* schar, int pos);  
int main()  
{  
    char pchar[] = "asderwsde";  
    char schar[] = "sde";  
  
    int cnt = 0;  
    int pos = 0;  
    int psz = sizeof(pchar);  
    int ssz = sizeof(schar);  
  
    while(pos < psz - ssz){  
        while(pchar[pos] != schar[0]){  
            ++pos;  
        }  
        if(pos > psz - ssz){           
            break;  
        }else{  
            if(matchsub(pchar, schar, pos)){  
                ++cnt;  
                ++pos;  
            }else{  
                ++pos;  
            }  
        }  
    }  
  
    if(cnt > 0){  
        cout << cnt <<" substring found!" << endl;  
    }  
  
  
    return 0;  
}  
  
bool matchsub(char* pchar, char* schar, int pos)  
{  
    bool flag = true;  
    int i = 0;  
    while(schar[i] != '\0' && pchar[pos+i] != '\0'){  
        if(pchar[pos+i] != schar[i]){  
            flag = false;  
            break;  
        }  
        ++i;  
    }  
    return flag;  
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值