2.string函數
find:某子串的起始位(0開始),函數的第二個參數使用代表從該位開始的后綴
substr:1) x開始的連續y位
2) x開始的后綴
#include<bits/stdc++.h> using namespace std; int main(){ string s1="abcdef"; string s2="de"; //find //返回位置 0起點 int ans=s1.find(s2); cout<<ans<<"\n"; //substr 1 //x位開始的連續y位 cout<<s1.substr(0,3)<<"\n"; //substr 2 //x開始的后綴 cout<<s1.substr(1)<<"\n"; return 0; }
string::npos 常數,作用類似於EOF,可以表示find函數未找到
getline(cin.a)輸入一整行
tolower,toupper是string單個字符轉換的函數
e.g:luogu 1308 統計單詞數
#include<bits/stdc++.h> using namespace std; string a,b; int main(){ getline(cin,a); getline(cin,b); for(int i=0;i<a.length();i++) a[i]=tolower(a[i]); for(int i=0;i<b.length();i++) b[i]=tolower(b[i]); a=' '+a+' '; b=' '+b+' '; if(b.find(a)==string::npos) printf("-1\n"); else{ int k=b.find(a),ans=0; int k1=b.find(a); while(k1!=string::npos){ ++ans;k1=b.find(a,k1+1);} printf("%d %d\n",ans,k);} return 0; }