สมมติว่าเรามีสตริง str เรามีตัวละครอื่น ch. งานของเราคือค้นหาดัชนีสุดท้ายของ ch ในสตริง สมมติว่าสตริงคือ "สวัสดี" และอักขระ 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