Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Searching Algorithms
  • MCQs on Searching Algorithms
  • Tutorial on Searching Algorithms
  • Linear Search
  • Binary Search
  • Ternary Search
  • Jump Search
  • Sentinel Linear Search
  • Interpolation Search
  • Exponential Search
  • Fibonacci Search
  • Ubiquitous Binary Search
  • Linear Search Vs Binary Search
  • Interpolation Search Vs Binary Search
  • Binary Search Vs Ternary Search
  • Sentinel Linear Search Vs Linear Search
Open In App
Next Article:
Count Occurrences of a Given Character in a String
Next article icon

Find last index of a character in a string

Last Updated : 27 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a string str and a character x, find last index of x in str.

Examples : 

Input : str = "geeks", x = 'e' Output : 2 Last index of 'e' in "geeks" is: 2   Input : str = "Hello world!", x = 'o' Output : 7 Last index of 'o' is: 7 
Recommended Practice
Last index of a character in the string
Try It!

Method 1 (Simple : Traverse from left): Traverse given string from left to right and keep updating index whenever x matches with current character. 

Implementation:

C++




// CPP program to find last index of
// character x in given string.
#include <iostream>
using namespace std;
 
// Returns last index of x if it is present.
// Else returns -1.
int findLastIndex(string& str, char x)
{
    int index = -1;
    for (int i = 0; i < str.length(); i++)
        if (str[i] == x)
            index = i;
    return index;
}
 
// Driver code
int main()
{
    // String in which char is to be found
    string str = "geeksforgeeks";
 
    // char whose index is to be found
    char x = 'e';
    int index = findLastIndex(str, x);
    if (index == -1)
        cout << "Character not found";
    else
        cout << "Last index is " << index;
    return 0;
}
 
 

Java




// Java program to find last index
// of character x in given string.
import java.io.*;
 
class GFG {
  
// Returns last index of x if
// it is present Else returns -1.
static int findLastIndex(String str, Character x)
{
    int index = -1;
    for (int i = 0; i < str.length(); i++)
        if (str.charAt(i) == x)
            index = i;
    return index;
}
  
// Driver code
public static void main(String[] args)
{
    // String in which char is to be found
    String str = "geeksforgeeks";
 
    // char whose index is to be found
    Character x = 'e';
 
    int index = findLastIndex(str, x);
    if (index == -1)
        System.out.println("Character not found");
    else
        System.out.println("Last index is " + index);
}
}
 
/* This code is contributed by Prerna Saini */
 
 

Python3




# A Python program to find last
# index of character x in given
# string.
 
# Returns last index of x if it
# is present. Else returns -1.
def findLastIndex(str, x):
    index = -1
    for i in range(0, len(str)):
        if str[i] == x:
            index = i
    return index
 
# Driver program
 
# String in which char is to be found
str = "geeksforgeeks"
 
# char whose index is to be found
x = 'e'
 
index = findLastIndex(str, x)
 
if index == -1:
    print("Character not found")
else:
    print('Last index is', index)
 
# This code is contributed by shrikant13.
 
 

C#




// C# program to find last index
// of character x in given string.
using System;
 
class GFG {
 
    // Returns last index of x if
    // it is present Else returns -1.
    static int findLastIndex(string str, char x)
    {
        int index = -1;
        for (int i = 0; i < str.Length; i++)
            if (str[i] == x)
                index = i;
        return index;
    }
     
    // Driver code
    public static void Main()
    {
        // String in which char is to be found
        string str = "geeksforgeeks";
     
        // char whose index is to be found
        char x = 'e';
     
        int index = findLastIndex(str, x);
        if (index == -1)
            Console.WriteLine("Character not found");
        else
            Console.WriteLine("Last index is " + index);
    }
}
 
/* This code is contributed by vt_m */
 
 

PHP




<?php
// PHP program to find last index of
// character x in given string.
 
// Returns last index of
// x if it is present.
// Else returns -1.
function findLastIndex($str, $x)
{
    $index = -1;
    for ($i = 0; $i < strlen($str); $i++)
        if ($str[$i] == $x)
            $index = $i;
    return $index;
}
 
// Driver code
// String in which
// char is to be found
$str = "geeksforgeeks";
 
// char whose index
// is to be found
$x = 'e';
$index = findLastIndex($str, $x);
if ($index == -1)
    echo("Character not found");
else
    echo("Last index is " . $index);
 
// This code is contributed by Ajit.
?>
 
 

Javascript




<script>
// javascript program to find last index
// of character x in given string.
 
// Returns last index of x if
// it is present Else returns -1.
function findLastIndex(str, x)
{
    let index = -1;
    for (let i = 0; i < str.length; i++)
        if (str[i] == x)
            index = i;
    return index;
}
   
 
// Driver code
 
    // String in which char is to be found
    let str = "geeksforgeeks";
   
    // char whose index is to be found
    let x = 'e';
   
    let index = findLastIndex(str, x);
    if (index == -1)
        document.write("Character not found");
    else
       document.write("Last index is " + index);
      
     // This code is contributed by sanjoy_62.
</script>
 
 
Output
Last index is 10

Time Complexity : O(n)
Auxiliary Space: O(1)

Method 2 (Efficient : Traverse from right): In above method 1, we always traverse complete string. In this method, we can avoid complete traversal in all those cases when x is present. The idea is to traverse from right side and stop as soon as we find character. 

Implementation:

CPP




// Simple CPP program to find last index of
// character x in given string.
#include <iostream>
using namespace std;
 
// Returns last index of x if it is present.
// Else returns -1.
int findLastIndex(string& str, char x)
{
    // Traverse from right
    for (int i = str.length() - 1; i >= 0; i--)
        if (str[i] == x)
            return i;
 
    return -1;
}
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
    char x = 'e';
    int index = findLastIndex(str, x);
    if (index == -1)
        cout << "Character not found";
    else
        cout << "Last index is " << index;
    return 0;
}
 
 

Java




// Java code to find last index
// character x in given string.
import java.io.*;
class GFG {
  
// Returns last index of x if
// it is present. Else returns -1.
static int findLastIndex(String str, Character x)
{
    // Traverse from right
    for (int i = str.length() - 1; i >= 0; i--)
        if (str.charAt(i) == x)
            return i;
 
    return -1;
}
  
// Driver code
public static void main(String[] args)
{
    String str = "geeksforgeeks";
    Character x = 'e';
    int index = findLastIndex(str, x);
    if (index == -1)
        System.out.println("Character not found");
    else
        System.out.println("Last index is " + index);
}
}
// This code is contributed by Prerna Saini
 
 

Python3




# Simple Python3 program to find last
# index of character x in given string.
 
# Returns last index of x if it is
# present. Else returns -1.
def findLastIndex(str, x):
 
    # Traverse from right
    for i in range(len(str) - 1, -1,-1):
        if (str[i] == x):
            return i
 
    return -1
 
# Driver code
str = "geeksforgeeks"
x = 'e'
index = findLastIndex(str, x)
 
if (index == -1):
    print("Character not found")
else:
    print("Last index is " ,index)
 
# This code is contributed by Smitha
 
 

C#




// C# code to find last index
// character x in given string.
using System;
 
class GFG {
 
    // Returns last index of x if
    // it is present. Else returns -1.
    static int findLastIndex(string str, char x)
    {
        // Traverse from right
        for (int i = str.Length - 1; i >= 0; i--)
            if (str[i] == x)
                return i;
     
        return -1;
    }
     
    // Driver code
    public static void Main()
    {
        string str = "geeksforgeeks";
        char x = 'e';
        int index = findLastIndex(str, x);
        if (index == -1)
            Console.WriteLine("Character not found");
        else
            Console.WriteLine("Last index is " + index);
    }
}
// This code is contributed by vt_m
 
 

PHP




<?php
// Simple PHP program to find last index
// of character x in given string.
 
// Returns last index of x if it
// is present. Else returns -1.
function findLastIndex($str, $x)
{
     
    // Traverse from right
    for ($i = strlen($str) - 1; $i >= 0; $i--)
        if ($str[$i] == $x)
            return $i;
 
    return -1;
}
 
// Driver code
$str = "geeksforgeeks";
$x = 'e';
$index = findLastIndex($str, $x);
if ($index == -1)
    echo("Character not found");
else
    echo("Last index is " . $index);
 
// This code is contributed by Ajit.
?>
 
 

Javascript




 
 
Output
Last index is 10

Time Complexity : O(n) 
Auxiliary Space: O(1)

 



Next Article
Count Occurrences of a Given Character in a String

A

Aarti_Rathi
Improve
Article Tags :
  • DSA
  • Searching
  • Strings
  • Technical Scripter
Practice Tags :
  • Searching
  • Strings

Similar Reads

  • Find Minimum Indexed Character in String
    Given a string str and another string patt. The task is to find the character in patt that is present at the minimum index in str. If no character of patt is present in str then print "$". Examples: Input: str = "geeksforgeeks", patt = "set" Output: e Both e and s of patt are present in str, but e i
    14 min read
  • Find one extra character in a string
    Given two strings which are of lengths n and n+1. The second string contains all the characters of the first string, but there is one extra character. Your task is to find the extra character in the second string. Examples: Input : string strA = "abcd"; string strB = "cbdae"; Output : e string B con
    15+ min read
  • Replace a character at a specific index in a String in Java
    In Java, here we are given a string, the task is to replace a character at a specific index in this string. Examples of Replacing Characters in a StringInput: String = "Geeks Gor Geeks", index = 6, ch = 'F'Output: "Geeks For Geeks."Input: String = "Geeks", index = 0, ch = 'g'Output: "geeks"Methods t
    3 min read
  • Count Occurrences of a Given Character in a String
    Given a string S and a character 'c', the task is to count the occurrence of the given character in the string. Examples: Input : S = "geeksforgeeks" and c = 'e'Output : 4Explanation: 'e' appears four times in str. Input : S = "abccdefgaa" and c = 'a' Output : 3Explanation: 'a' appears three times i
    6 min read
  • Accessing characters by index in a String
    Given two strings str1 and an index, the task is to access the character at this index. Examples: Input: str = "hello", index = 1Output: e Input: str = "GfG", index = 2Output: G Accessing characters by index in a string:Individual characters in a string can be accessed by specifying the string name
    2 min read
  • Find repeated character present first in a string
    Given a string, find the repeated character present first in the string.(Not the first repeated character, found here.) Examples: Input : geeksforgeeks Output : g (mind that it will be g, not e.) Asked in: Goldman Sachs internship Simple Solution using O(N^2) complexity: The solution is to loop thro
    15 min read
  • Remove odd indexed characters from a given string
    Given string str of size N, the task is to remove the characters present at odd indices (0-based indexing) of a given string. Examples : Input: str = “abcdef”Output: aceExplanation:The characters 'b', 'd' and 'f' are present at odd indices, i.e. 1, 3 and 5 respectively. Therefore, they are removed f
    4 min read
  • Find maximum occurring character in a string
    Given string str. The task is to find the maximum occurring character in the string str. Examples: Input: geeksforgeeksOutput: eExplanation: 'e' occurs 4 times in the string Input: testOutput: tExplanation: 't' occurs 2 times in the string Return the maximum occurring character in an input string us
    9 min read
  • Find the Nth occurrence of a character in the given String
    Given string str, a character ch, and a value N, the task is to find the index of the Nth occurrence of the given character in the given string. Print -1 if no such occurrence exists. Examples: Input: str = "Geeks", ch = 'e', N = 2 Output: 2 Input: str = "GFG", ch = 'e', N = 2 Output: -1 Recommended
    7 min read
  • Find i'th Index character in a binary string obtained after n iterations
    Given a decimal number m, convert it into a binary string and apply n iterations. In each iteration, 0 becomes "01" and 1 becomes "10". Find the (based on indexing) index character in the string after the nth iteration. Examples: Input : m = 5, n = 2, i = 3Output : 1Input : m = 3, n = 3, i = 6Output
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences