在C ++中查找字符串中字符的最后一个索引
假设我们有一个字符串str。我们还有另一个字符ch。我们的任务是找到字符串中ch的最后一个索引。假设字符串为“Hello”,字符ch='l',则最后一个索引为3。
为了解决这个问题,我们将从右到左遍历列表,如果字符与'l'不同,则减少索引,如果匹配,则停止并返回结果。
示例
#include<iostream>
using namespace std;
int getLastIndex(string& str, char ch) {
for (int i = str.length() - 1; i >= 0; i--)
if (str[i] == ch)
return i;
return -1;
}
int main() {
string str = "hello";
char ch = 'l';
int index = getLastIndex(str, ch);
if (index == -1)
cout << "Character not found";
else
cout << "Last index is " << index;
}输出结果
Last index is 3
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短