Practical Examples and Use Cases
The ability to find the last occurrence of a character in a string can be useful in a variety of scenarios. Let's explore some practical examples and use cases:
Reversing a String
One common use case for the lastIndexOf()
method is to reverse a string. By iterating through the string from the last index to the first, you can build a new string that represents the reverse of the original.
String originalString = "LabEx";
StringBuilder reversedString = new StringBuilder();
for (int i = originalString.length() - 1; i >= 0; i--) {
reversedString.append(originalString.charAt(i));
}
System.out.println("Original string: " + originalString);
System.out.println("Reversed string: " + reversedString.toString());
Output:
Original string: LabEx
Reversed string: xEbaL
Removing Duplicates from a String
Another use case for the lastIndexOf()
method is to remove duplicate characters from a string. By iterating through the string and keeping track of the last index of each character, you can build a new string that contains only the unique characters.
String originalString = "LabExLabEx";
StringBuilder uniqueString = new StringBuilder();
boolean[] charFound = new boolean[128]; // Assuming ASCII characters
for (int i = 0; i < originalString.length(); i++) {
char c = originalString.charAt(i);
if (!charFound[c]) {
uniqueString.append(c);
charFound[c] = true;
}
}
System.out.println("Original string: " + originalString);
System.out.println("Unique string: " + uniqueString.toString());
Output:
Original string: LabExLabEx
Unique string: LabEx
Replacing the Last Occurrence of a Character
The lastIndexOf()
method can also be used to replace the last occurrence of a character in a string. This can be useful in scenarios where you need to update or modify a specific part of a string.
String originalString = "LabEx is a great platform for learning Java";
String modifiedString = originalString.substring(0, originalString.lastIndexOf('a')) + "o";
System.out.println("Original string: " + originalString);
System.out.println("Modified string: " + modifiedString);
Output:
Original string: LabEx is a great platform for learning Java
Modified string: LabEx is a great platform for learning Jovo
In this example, the lastIndexOf()
method is used to find the index of the last occurrence of the character 'a'
. The string is then split into two parts: the part before the last 'a'
and the part after it. The last part is then replaced with the character 'o'
to create the modified string.
These examples demonstrate how the lastIndexOf()
method can be used to solve various string-related problems in your Java applications.