突然发现了find函数的妙处

题目:字母王国已经陷入混乱中了,所有的字母都已经无序了,但有些特定的序列是极其有价值的,你能确定这种有价值的连续序列是否存在吗?

输入:输入两行字符串,每一行是一串仅有小写英文字母组成的字符串。

输出:如果第一串字符串中存在第二串字符串,则输出第二串字符串,否则输出“What a pity!”。

我一开始写的代码比较麻烦,如下:

#include<iostream>
#include<cstring>
using namespace std;
int main()
{	
    string a, b;	
    int flag = 1, ok = 0, j = 0;	
    cin >> a >> b;	
    for (int i = 0; i < a.size(); i++)	
    {		
           int k = i, j = 0;		
           while (a[k] == b[j] && k < a.size() && j < 
b.size())	  
          {			
              j++, k++;		
          }		
     if (j == b.size())
         { 
            flag = 0; break;
         }	
    }	
      if (!flag)		
          cout << b << endl;
      else		
          cout << "What a pity!" << endl;	
     return 0;
     }
后来发现了find函数,开心坏了。代码如下: 
 #include<iostream>
#include<cstring>
using namespace std;
int main()
{	
      string a,b;	
      cin >> a;	
      cin >> b;
      if (a.find(b) != string::npos)		
          cout << b << endl;
      else		
          cout << "What a pity!" << endl;
  	  return 0;
  }

我观看了以下的find函数的介绍,懂得了很多(以下是转载内容)
1.find()

查找第一次出现的目标字符串:

#include<iostream>

#include<cstdio>

using namespace std;
int main(){

string s1 = "abcdef";

string s2 = "de";

int ans = s1.find(s2) ;   //在S1中查找子串S2

cout<<ans<<endl;

system("pause");

}

说明:如果查找成功则输出查找到的第一个位置,否则返回-1;

查找从指定位置开始的第一次出现的目标字符串:

#include<iostream>

#include<csdtio>

using namespace std;
int main(){

string s1 = "abcdef";

string s2 = "de";

int ans = s1.find(s2, 2) ;   //从S1的第二个字符开始查找子串S2

cout<<ans<<endl;

system("pause");

}

2.find_first_of()

查找子串中的某个字符最先出现的位置。find_first_of()不是全匹配,而find()是全匹配

#include<iostream>
#include<csdtio>
using namespace std;

int main(){

string s1 = "adedef";

string s2 = "dek";

int ans = s1.find_first_of(s2) ;   //在S1中查找子串S2

cout<<ans<<endl;

system("pause");

}

其中find_first_of()也可以约定初始查找的位置:s1.find_first_of(s2, 2) ;

3.find_last_of()

这个函数与find_first_of()功能差不多,只不过find_first_of()是从字符串的前面往后面搜索,而find_last_of()是从字符串的后面往前面搜索。

4.rfind()

反向查找字符串,即找到最后一个与子串匹配的位置

5.find_first_not_of()

找到第一个不与子串匹配的位置

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值