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