不用string 用string 方法对比
//1.1 不用string 纯笨办法
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
char word[11];
char str[1000001];//如果声明为局部变量,需memset
int pos=-1;//最早位置
bool check(int ps,int pa) {//ps字符串游标 pa单词游标
char t1,t2;
while(str[ps]!='\0'&&word[pa]!='\0') {
t1=min(str[ps],word[pa]);
t2=max(str[ps],word[pa]);
if(t1==t2||t1+32==t2) {//处理大小写
ps++;
pa++;
} else {
return false;
}
}
if((str[ps]==' '||str[ps]=='\0')&&word[pa]=='\0') return true;
else return false;
}
int main() {
freopen("stat.in","r",stdin);
freopen("stat.out","w",stdout);
cin>>word;
cin.get(); //过滤掉上一个cin最后的空格
cin.getline(str,1000000,'\n'); //第三个参数可不写
int len2=strlen(str); //需头文件cstring
int len1=strlen(word);
int ans=0;
int p;
for(int i=0; i<len2; i++) {
if(i==0) {
if(check(0,0)) {
if(pos==-1) pos=0;
ans++;
}
} else if(str[i]==' ') {
if(check(i+1,0)) {
if(pos==-1) pos=i+1;
ans++;
}
}
}
if(pos!=-1) cout<<ans<<" "<<pos<<endl;
else cout<<pos<<endl;
return 0;
}
//1.2先处理大小写问题,其他一样没变
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
//不用string 纯笨办法
char word[11];
char str[1000001];//如果声明为局部变量,需memset
int pos=-1;//最早位置
void ftolower(char a[],int size){//转换大小写
for(int i=0;i<size;i++){
a[i]=tolower(a[i]);//cctype
}
}
bool check(int ps,int pa) {//ps字符串游标 pa单词游标
while(str[ps]!='\0'&&word[pa]!='\0') {
if(str[ps]==word[pa]) {//处理大小写
ps++;
pa++;
} else {
return false;
}
}
if((str[ps]==' '||str[ps]=='\0')&&word[pa]=='\0') return true;
else return false;
}
int main() {
freopen("stat.in","r",stdin);
freopen("stat.out","w",stdout);
cin>>word;
cin.get(); //过滤掉上一个cin最后的空格
cin.getline(str,1000000,'\n'); //第三个参数可不写
int len2=strlen(str); //需头文件cstring
int len1=strlen(word);
ftolower(word,len1);ftolower(str,len2);
int ans=0;
for(int i=0; i<len2; i++) {
if(i==0) {
if(check(0,0)) {
if(pos==-1) pos=0;
ans++;
}
} else if(str[i]==' ') {
if(check(i+1,0)) {
if(pos==-1) pos=i+1;
ans++;
}
}
}
if(pos!=-1) cout<<ans<<" "<<pos<<endl;
else cout<<pos<<endl;
return 0;
}
//1.3 string substr string对比
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
//用string substr string对比
string word,text;
int firstp=-1;
int main() {
freopen("stat.in","r",stdin);
freopen("stat.out","w",stdout);
cin>>word;
cin.get(); //过滤掉上一个cin最后的空格
getline(cin,text);//该写法不用写大小 另一写法cin.getline()的对象得是char数组
for(int i=0;i<word.length();i++){
word[i]=tolower(word[i]);
}
for(int j=0;j<text.length();j++){
text[j]=tolower(text[j]);
}
int p1=0,ans=0; string strn;
for(int i=0;i<=text.length();i++){
if(text[i]==' '||text[i]=='\0'){//
strn=text.substr(p1,i-p1);
//cout<<word<<" "<<strn<<endl;
if(word==strn){// 可直接对比
if(firstp==-1){
firstp=p1;
}
ans++;
}
p1=i+1;
}
}
if(firstp!=-1) cout<<ans<<" "<<firstp;
else cout<<firstp;
fclose(stdin);fclose(stdout);
return 0;
}