在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP