巧用stringのfind函数

string的find函数用好了真的很方便,就和set函数一样秒杀一些题!

 1 void test8()
 2 {
 3     string s("dog bird chicken bird cat");
 4 
 5     //字符串查找-----找到后返回首字母在字符串中的下标
 6 
 7     // 1. 查找一个字符串
 8     cout << s.find("chicken") << endl;        // 结果是:9
 9 
10     // 2. 从下标为6开始找字符'i',返回找到的第一个i的下标
11     cout << s.find('i',6) << endl;            // 结果是:11
12 
13     // 3. 从字符串的末尾开始查找字符串,返回的还是首字母在字符串中的下标
14     cout << s.rfind("chicken") << endl;       // 结果是:9
15 
16     // 4. 从字符串的末尾开始查找字符
17     cout << s.rfind('i') << endl;             // 结果是:18-------因为是从末尾开始查找,所以返回第一次找到的字符
18 
19     // 5. 在该字符串中查找第一个属于字符串s的字符
20     cout << s.find_first_of("13br98") << endl;  // 结果是:4---b
21 
22     // 6. 在该字符串中查找第一个不属于字符串s的字符------先匹配dog,然后bird匹配不到,所以打印4
23     cout << s.find_first_not_of("hello dog 2006") << endl; // 结果是:4
24     cout << s.find_first_not_of("dog bird 2006") << endl;  // 结果是:9
25 
26     // 7. 在该字符串最后中查找第一个属于字符串s的字符
27     cout << s.find_last_of("13r98") << endl;               // 结果是:19
28 
29     // 8. 在该字符串最后中查找第一个不属于字符串s的字符------先匹配t--a---c,然后空格匹配不到,所以打印21
30     cout << s.find_last_not_of("teac") << endl;            // 结果是:21
31 
32 }

 

P1628 合并序列 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

这道题就完全可以用string的find函数秒杀!巨爽

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int N=1e5+100;
 4 string a[N],k;
 5 
 6 int main()
 7 {
 8     int n; cin>>n;
 9     for(int i=1;i<=n;i++)cin>>a[i];
10     cin>>k;
11     sort(a+1,a+1+n);
12     
13     for(int i=1;i<=n;i++)
14     {
15         if(a[i].find(k)==0)    //k的第一个字母位于string的坐标0,说明是前缀 
16             cout<<a[i]<<endl;
17     }
18     
19     return 0;
20 }
View Code

 

posted @ 2022-03-20 14:09  wellerency  阅读(92)  评论(0编辑  收藏  举报