C++ 字符串查找:寻找指定字符

问题描述: 从给定字符串中查找某指定的字符。

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

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

思路: 遍历字符串,判断是否与待查找的字符相等,如果相等则更新下标。如果遍历完字符串后下标未更新,则说明未找到该字符。

C++ 代码:

#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;
}
C++ 字符串查找:寻找指定字符

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

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