C++ 字符串查找:寻找指定字符的最大下标
C++ 字符串查找:寻找指定字符的最大下标
问题描述:
本题要求编写 C++ 程序,从给定字符串中查找某指定的字符。
输入格式:
输入的第一行是一个待查找的字符。第二行是一个以回车结束的非空字符串(不超过 80 个字符)。
输出格式:
如果找到,在一行内按照格式 'index = 下标' 输出该字符在字符串中所对应的最大下标(下标从 0 开始);否则输出 'Not Found'。
解题思路:
首先读入待查找的字符和字符串,然后用一个变量记录该字符最后一次出现的位置(下标)。遍历字符串的每一个字符,若与待查找的字符相等,则更新记录位置的变量。最后判断该变量是否被更新,如果被更新则输出记录位置的变量,否则输出 'Not Found'。
参考代码:
#include <iostream>
#include <string>
using namespace std;
int main() {
char targetChar;
string str;
cin >> targetChar >> str;
int lastIndex = -1;
for (int i = 0; i < str.length(); i++) {
if (str[i] == targetChar) {
lastIndex = i;
}
}
if (lastIndex != -1) {
cout << "index = " << lastIndex << endl;
} else {
cout << "Not Found" << endl;
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/mGGF 著作权归作者所有。请勿转载和采集!