字符串判等
由于有空格,所以用getline函数是一个很好的选择。在循环查找字符时先设计一个空格检测,非空格的字符先转小写再将其赋值新的字符串t1(即整理后的字符串)。再利用strcmp函数进行判断。
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s1,s2;
string t1 = "",t2 = "";
getline(cin,s1);//读取一整行输入
for (char &c : s1)
{
if(c != ' '){t1 += tolower(c);}
}
getline(cin,s2);
for (char &c : s2)
{
if(c != ' '){t2 += tolower(c);}
}
//cout << t1 << endl << t2 << endl;
if(strcmp(t1.c_str(),t2.c_str()) == 0){cout << "YES" << endl;}
else cout << "NO" << endl;
return 0;
}
依旧利用getline函数读取输入。然后利用find函数即可。
注意: //".find()"函数,"string::npos"是其查找失败返回值.
// "s2.find(s1)" 在s2中查找s1.
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s1,s2;
getline(cin,s1);//读取一整行输入
getline(cin,s2);
//".find()"函数,"string::npos"是其查找失败返回值.
// "s2.find(s1)" 在s2中查找s1.
if(s2.find(s1) != string::npos){cout << s1 << " is substring of " << s2 << endl;}
else if(s1.find(s2) != string::npos){cout << s2 << " is substring of " << s1 << endl;}
else cout << "No substring" <<endl;
return 0;
}