题目来源:- 计算机软件能力认证考试系统
1、采用string自带的str.find(key)函数进行求解。如果大小写不敏感,则把匹配和被匹配的字符都转换成小写再进行匹配
#include<bits/stdc++.h>
using namespace std;
int main() {
string key, s, kt, st;
int option, n;
// 输入数据
cin >> key >> option >> n;
// 获得key的小写字符串,放在变量kt
kt = key;
for(int i=0; i<(int)kt.size(); i++)
if(isupper(kt[i]))
kt[i] = tolower(kt[i]);
// 循环处理
for(int i=1; i<=n; i++) {
cin >> s;
if(option == 0) { // 大小写无关
st = s;
for(int i=0; i<(int)st.size(); i++)
if(isupper(st[i]))
st[i] = tolower(st[i]);
int pos = st.find(kt);
if(pos >= 0)
cout << s << endl;
} else { // 大小写有关
int pos = s.find(key);
if(pos >= 0)
cout << s << endl;
}
}
return 0;
}
2、采用函数strstr(str,key)进行求解。
#include<bits/stdc++.h>
using namespace std;
int main() {
char key[100],lowerkey[100],lowers[100],s[100];
int n,m;
cin>>key>>n>>m;
strcpy(lowerkey,key);
strlwr(lowerkey); //将字符串转换为小写
while(cin>>s) {
if(n==0) {
strcpy(lowers,s);
strlwr(lowers);
if(strstr(lowers,lowerkey)) //匹配
cout<<s<<endl;
} else {
if(strstr(s,key))
cout<<s<<endl;
}
}
return 0;
}