C++ 字符串查找:找到指定字符的最后一次出现位置

问题描述: 从给定的字符串中查找指定的字符,并输出其最后一次出现的位置(下标)。

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

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

解题思路: 直接使用 string 的 find_last_of 函数查找指定字符最后一次出现的位置即可。

C++ 代码:

#include <iostream>
#include <string>

using namespace std;

int main() {
  char target;
  string str;

  cin >> target >> str;

  size_t index = str.find_last_of(target);

  if (index != string::npos) {
    cout << "index = " << index << endl;
  } else {
    cout << "Not Found" << endl;
  }

  return 0;
}

代码说明:

  1. find_last_of(target) 函数用于查找字符 target 在字符串 str 中最后一次出现的位置,并返回其下标。如果找不到,则返回 string::npos
  2. 如果 index 不等于 string::npos,则说明找到了字符 target,输出其下标。
  3. 否则,输出 'Not Found'。

原文地址: https://www.cveoy.top/t/topic/mGGZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录