字串查找以及统计字串次数

大四找工作了,总要面临着做笔试题这类的,这不本人接连几次都遇到,可是无奈自己每次都做不到,终于有一天花了一点时间写了下,希望对有些人有帮助。
#include <stdio.h>
#include <stdlib.h>


int strlen(const char *p){
    int i;
    int nLen;
    if(NULL == p){
	return -1;
    }
    nLen = 0;
    for(i = 0;p[i] != '\0';i++){
	nLen++;
    }

    return nLen;
}

int find_str(const char *pSrc,char *pDest,int index){
    const char *pSTemp;
    char *pDTemp;
    int nPos;
    int i,j;

    if(NULL == pSrc || NULL == pDest){
	return -1;
    }
    if(index > strlen(pSrc)){
	return -1;
    }
    pSTemp = pSrc;
    pDTemp = pDest;
    for(i = index,j = 0;pSTemp[i] != '\0' && pDTemp[j] != '\0';i++,j++){
	if(pSTemp[i] == pDTemp[j]){
	    nPos = i;
	}else{
	    j = -1;
            pDTemp = pDest;
	    
	}
    }
    if(pSTemp[i] == '\0' && pDTemp[j] != '\0'){
	return -1;
    }
    
   return (nPos - strlen(pDest) +1);
}

int cllect_times(const char *p,char *q){
    int nTimes;
    int nPos;
    int nLen;
    if(NULL == p && NULL == q){
	return -1;
    }
    nPos = find_str(p,q,0);
    nLen = strlen(q);
    nTimes = -1;
    if(nPos >= 0){
	printf("the pos: %d\n",nPos);
	nTimes++;
	while(nPos >= 0){
	    nPos = find_str(p,q,(nPos+nLen));
	    nTimes++;
	    if(nPos  > 0){
	    printf("the pos: %d\n",nPos);
	    }
	}
    }
    return nTimes;
}
    
int main(){

//test strlen:
char *p = "abcdabefab";
char *q = "ab";
int i = cllect_times(p,q);
printf("times == %d\n",i);
    return 0;
}


   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值