
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find last index of a character in a string in C++
Suppose we have a string str. We have another character ch. Our task is to find the last index of ch in the string. Suppose the string is “Hello”, and character ch = ‘l’, then the last index will be 3.
To solve this, we will traverse the list from right to left, if the character is not same as ‘l’, then decrease index, if it matches, then stop and return result.
Example
#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; }
Output
Last index is 3
- Related Articles
- MySQL String Last Index Of in a URL?
- Search index of a character in a string in Java
- How to find the last index value of a string in Golang?
- How to find index of last occurrence of a substring in a string in Python?
- Finding the last occurrence of a character in a String in Java
- Return index of first repeating character in a string - JavaScript
- Find the index of the first unique character in a given string using C++
- Queries to find the last non-repeating character in the sub-string of a given string in C++
- Find the last non repeating character in string in C++
- Get the index of last substring in a given string in MySQL?
- Find i’th index character in a binary string obtained after n iterations in C++
- Find i’th Index character in a binary string obtained after n iterations in C++ programming
- Take off last character if a specific one exists in a string?
- Finding the index of the first repeating character in a string in JavaScript
- Getting last 5 character of a string with MySQL query?

Advertisements