在 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
廣告