#include<iostream>
using namespace std;
int strlen(char *p1)
{
int i=0;
while(*p1++)
i++;
return i;
}
int find_substr(char* s1,char* s2)
{
int la;
int lb;
int i;
int j;
la=strlen(s1);
lb=strlen(s2);
for(i=0;(la-i)>=lb;i++)
{
if(s1[i]==s2[0])
{
for(j=0;j<=lb;j++)
{
if(s1[i+j]!=s2[j])
break;
if(j==lb)
return 1;
}
}
}
}
void main()
{
char s1[100];
char s2[100];
gets(s1);
gets(s2);
cout<<find_substr(s1,s2)<<endl;
if(find_substr(s1,s2)==1)
cout<<"有子字符串"<<endl;
else
cout<<"没有子字符串"<<endl;
}
做出来有错误函数哪里错了
c++ string.find函数
string (1) size_t find (const string& str, size_t pos = 0) const;
c-string (2) size_t find (const char* s, size_t pos = 0) const;
buffer (3) size_t find (const char* s, size_t pos, size_t n) const;
character (4) size_t find (char c, size_t pos = 0) const;
例子:
// string::find#include <iostream> // std::cout
#include <string> // std::string
int main ()
{
std::string str ("There are two needles in this haystack with needles.");
std::string str2 ("needle");
// different member versions of find in the same order as above:
std::size_t found = str.find(str2);
if (found!=std::string::npos)
std::cout << "first 'needle' found at: " << found << '\n';
found=str.find("needles are small",found+1,6);
if (found!=std::string::npos)
std::cout << "second 'needle' found at: " << found << '\n';
found=str.find("haystack");
if (found!=std::string::npos)
std::cout << "'haystack' also found at: " << found << '\n';
found=str.find('.');
if (found!=std::string::npos)
std::cout << "Period found at: " << found << '\n';
// let's replace the first needle:
str.replace(str.find(str2),str2.length(),"preposition");
std::cout << str << '\n';
return 0;
}
结果:
first 'needle' found at: 14second 'needle' found at: 44
'haystack' also found at: 30
Period found at: 51
There are two prepositions in this haystack with needles.
s1未必一定比s2长,需要判断一下。
for(i=0;(la-i)>=lb;i++) 和 for(j=0;j<=lb;j++) 可能会导致越界,把=号去掉试一下。数组下标从0开始,不能等于有效元素个数。在这段程序里,应该是把结束的\0也参与比较了。
{
int i=0;
while(*p1++)
i++;
return i;
}
里的 while(*p1++) 改成 while (*p1++!='\0')