Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม 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