1.给出一个函数来复制两个字符串A和B。
字符串A的后几个字节和字符串B的前几个字节重叠。
分析:记住,这种题目往往就是考你对边界的考虑情况。
2.已知一个字符串,比如asderwsde,寻找其中的一个子字符串比如sde的个数,
如果没有返回0,有的话返回子字符串的个数
1.解答:
memmove类似,如果有重叠,则考虑从后往前复制,以免覆盖导致字符丢失,还有就是考虑空等特殊情况的处理
2.解答:
方法一:KMP_count算法
#include<iostream>
#include<stdlib.h>
#include<vector>
using namespace std;
inline void NEXT(const string &T,vector<int> &next)
{
//按模式串生成vector,next(T.size())
next[0]=-1;
int i=0;
int j=-1;
while(i<T.size()-1)
{
if (j==-1||T[i]==T[j])
{
++i;
++j;
next[i]=j;
}
else
j=next[j];
}
}
inline string::size_type COUNT_KMP(const string &S,
const string &T)
{
//利用模式串T的next函数求T在主串S中的个数count的KMP算法
//其中T非空,
vector<int> next(T.size());
NEXT(T,next);
string::size_type index,count=0;
for(index=0;index<S.size();++index)
{
int pos=0;
string::size_type iter=index;
while(pos<T.size()&&iter<S.size()){
if(S[iter]==T[pos]){
++iter;++pos;
}
else
{
if(pos==0) ++iter;
else pos=next[pos-1]+1;
}
}
if(pos==T.size()&&(iter-index)==T.size()) ++count;
if(pos==T.size()&&(iter-index)>T.size()) index=iter-T.size()-1;
}
return count;
}
int main(int argc,char *argv[])
{
string S="BAHHHBAHHHBA";
string T="BA";
string::size_type count=COUNT_KMP(S,T);
cout<<count<<endl;
system("PAUSE");
return 0;
}
方法二:strstr 找到之后 des串往后移动一位,继续执行strstr
方法三:strncmp函数
int count_of_substr(const char* str, const char * sub) {
int count = 0;
char * p = str;
int n = strlen(sub);
while ( *p != ‘\0’ ) {
if (strncmp(p, sub, n) == 0) count ++;
p++;
}
return count;
}