C++ 字符串查找:查找指定字符并输出下标

问题描述:

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

输入格式:

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

输出格式:

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

解题思路:

  1. 先输入待查找的字符和字符串。
  2. 遍历字符串,如果找到待查找的字符就更新下标。
  3. 最后判断是否找到,并输出结果。

参考代码:

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

int main() {
    char targetChar;
    string str;
    cin >> targetChar >> str;
    int index = -1;
    for (int i = 0; i < str.length(); i++) {
        if (str[i] == targetChar) {
            index = i;
        }
    }
    if (index != -1) {
        cout << "index = " << index << endl;
    } else {
        cout << "Not Found" << endl;
    }
    return 0;
}

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

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