For example, in the string:
"hello world",
the last occurrence of the find last occurrence of character in string character 'o' is at index 7 (zero-based index).
Methods to Find the Last Occurrence
Different programming languages offer various ways to accomplish this:
1. Python
Python provides the .rfind() and .rindex() methods:
python
Copy
Edit
text = "hello world"
position = text.rfind('o') # Returns 7
print(position)
.rfind() returns the highest index of the character or -1 if not found.
.rindex() works similarly but raises an error if the character is absent.
2. Java
Java uses the .lastIndexOf() method:
java
Copy
Edit
public class Main {
public static void main(String[] args) {
String text = "hello world";
int position = text.lastIndexOf('o');
System.out.println(position); // Output: 7
}
}
This function returns -1 if the character is not found.
3. JavaScript
JavaScript also provides the .lastIndexOf() function:
javascript
Copy
Edit
let text = "hello world";
let position = text.lastIndexOf('o');
console.log(position); // Output: 7
4. C/C++
In C, the strrchr() function is commonly used:
c
Copy
Edit
#include <stdio.h>
#include <string.h>
int main() {
char text[] = "hello world";
char *ptr = strrchr(text, 'o');
if (ptr != NULL)
printf("Last occurrence: %ld\n", ptr - text);
else
printf("Character not found\n");
return 0;
}
This function returns a pointer to the last occurrence of the character.
Real-World Applications
File Path Extraction – Finding the last occurrence of '/' or '\' in a file path helps extract file names.
Parsing Data – Used in log file processing and string manipulation.
Text Analysis – Locating the last occurrence of punctuation or delimiters.