【发布时间】:2015-04-21 10:14:14
【问题描述】:
int main(){
string s1="gandalf";
string s2="dal";
function(s1,s2);
return 0;
}
函数中,如果字符串s1中有“dal”,则返回1。 否则返回 0
【问题讨论】:
-
是什么让您无法简单地阅读
std::string文档?
int main(){
string s1="gandalf";
string s2="dal";
function(s1,s2);
return 0;
}
函数中,如果字符串s1中有“dal”,则返回1。 否则返回 0
【问题讨论】:
std::string 文档?
试试下面的
bool function( const std::string &s1, const std::string &s2 )
{
return s1.find( s2 ) != std::string::npos;
}
如果你想使用循环自己编写函数,那么它可以如下所示
#include <iostream>
#include <iomanip>
#include <string>
bool function( const std::string &s1, const std::string &s2 )
{
bool found = false;
if ( !( s1.size() < s2.size() ) && !s2.empty() )
{
for ( size_t i = 0; !found && i < s1.size() - s2.size() + 1; i++ )
{
size_t j = 0;
while ( j < s2.size() && s1[i+j] == s2[j] ) ++j;
found = j == s2.size();
}
}
return found;
}
int main()
{
std::string s1 = "gandalf";
std::string s2 = "dal";
std::cout << std::boolalpha << function( s1, s2 ) << std::endl;
return 0;
}
程序输出是
true
【讨论】:
void fonk(string a, string b){
char x[10],y[10];
for(int i=0;i<10;i++)
x[i]=a[i];
for(int i=0;i<10;i++)
y[i]=b[i];
for(int j=0;j<10;j++){
if(x[j]==y[0]&&x[j+1]==y[1]&&x[j+2]==y[2])
cout<<"true"<<endl;
else
cout<<"false"<<endl;
} }
【讨论】: