luogu1308
一道字符串题
用string
头文件
#include <cstdio> #include <iostream> #include <cstring>
声明
string s1;
读入
读一行
getline(cin, s);
字符串的截取
string tmp = string(s, 0, 5);//s不解释,0为起始位置,5为截取长度。
引用
s[i]//和数组一样
比较
if (s1 == s2) { //do sth. } //直接来就可以了。
最后AC代码:
#include <cstdio> #include <iostream> #include <cstring> using namespace std; const int maxn = 1000000 + 5; int a[maxn]; int main() { // freopen("luogu1308.in","r",stdin); string t1, t2; getline(cin, t1); getline(cin, t2); int l1 = t1.length(); if (t1[l1 - 1] == ' ')t1 = string(t1, 0, l1 - 1); // cout << t1 << endl; int l2 = t2.length(); for (int i = 0; i < l1; i++) t1[i] = tolower(t1[i]); int count = 0; for (int i = 0; i < l2; i++) { t2[i] = tolower(t2[i]); if (t2[i] == ' ') { a[++count] = i; //记录空格的位置。 } } int cnt = 0, flag = 0, js = -1; // cout << t1; string tmp = string(t2, 0, a[1] - 0); // cout << tmp << endl; if (tmp == t1) { flag = 1; cnt++; js = 0; } for (int i = 1; i <= count - 1; i++) { string tmp = string(t2, a[i] + 1, a[i + 1] - a[i] - 1); // printf("%d\n", tmp.length()); // printf("%d\n", t1.length()); // cout << tmp << endl; // cout << t1 << endl; if (tmp == t1) { cnt++; if (!flag) js = a[i] + 1;//第一次找到。 flag = 1; } } if (flag) { printf("%d %d\n", cnt, js); } else { printf("-1\n"); } return 0; }