PTA - 查找指定字符【泛型算法】

查找指定字符

题目:本题要求编写程序,从给定字符串中查找某指定的字符。

输入格式:

输入的第一行是一个待查找的字符。第二行是一个以回车结束的非空字符串(不超过80个字符)。

输出格式:

如果找到,在一行内按照格式 “index = 下标” 输出该字符在字符串中所对应的最大下标(下标从0开始);否则输出"Not Found"。

输入样例1:

m
programming

输出样例1:

index = 7

输入样例2:

a
1234

输出样例2:

Not Found

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

int main()
{
    char ch;
    cin >> ch;
    cin.ignore();   // 或 getchar();

    string s;
    getline(cin, s);
    
    int index = 0;
    for (int i = 0; i != '\n'; i++)  
    {
  	index = s.find_last_of(ch);
	//index = s.rfind(ch);  
    }
    
    if (index != -1) 
        cout << "index = " << index;
    else
        cout << "Not Found";
 
 return 0;
 }

小结:

1.find(): 查找第一次出现的目标字符串
2.find_first_of():查找子串中的某个字符c最先出现的位置
3.find_last_of():从后往前查找字串中某个字符c出现的位置
4.rfind():反向查找,即找到最后一个与子串匹配的位置
5.find_first_not_of():查找第一个不匹配的位置

猜你喜欢

转载自blog.csdn.net/weixin_43821410/article/details/89380648
PTA