Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

In various text processing tasks, it’s common to encounter scenarios where we need to find the nth last occurrence of a specific character within a given string. Moreover, this operation can be particularly useful in tasks such as parsing logs, analyzing textual data, or extracting relevant information from strings.

In this tutorial, we’ll explore various techniques to find the nth last occurrence of a character in a string using Java.

2. Using Traditional Looping

One conventional approach to finding the nth last occurrence of a character in a string is through iterative looping. In this approach, we iterate through the string from the end, counting occurrences of the target character until we reach the desired position.

Let’s see how this can be implemented:

String str = "Welcome to Baeldung";
char target = 'e';
int n = 2;
int expectedIndex = 6;

@Test
public void givenStringAndCharAndN_whenFindingNthLastOccurrence_thenCorrectIndexReturned() {
    int count = 0;
    int index = -1;
    for (int i = str.length() - 1; i >= 0; i--) {
        if (str.charAt(i) == target) {
            count++;
            if (count == n) {
                index = i;
                break;
            }
        }
    }
    assertEquals(expectedIndex, index);
}

In this test method, we systematically iterate over the characters of the string str in reverse order. So, we create variables such as count to track occurrences and index to store the index of the desired occurrence, and we meticulously manage the search process.

Moreover, each character is inspected to determine if it matches the target character, incrementing the count variable accordingly until the desired nth occurrence is reached.

Finally, we validate that the obtained index corresponds accurately to the expectedIndex, ensuring the correctness of our implementation.

3. Using Java Streams and IntStream

Another approach involves using Java streams and the IntStream class to manipulate character indices in the string. Here’s an example:

@Test
public void givenStringAndCharAndN_whenFindingNthLastOccurrenceUsingStreams_thenCorrectIndexReturned() {
    OptionalInt result = IntStream.range(0, str.length())
      .map(i -> str.length() - 1 - i)
      .filter(i -> str.charAt(i) == target)
      .skip(n - 1)
      .findFirst();
    int index = result.orElse(-1);
    assertEquals(expectedIndex, index);
}

In this test method, we adopt a functional programming approach, leveraging the IntStream.range() method to generate a stream of integer indices representing the characters of the input string. Then, we map each index to its position at the end of the string, facilitating traversal in reverse order.

Subsequently, we apply a filtering operation to retain only those indices where the corresponding character matches the target character. By employing the skip(n-1) method, we bypass the initial occurrences and then use findFirst() to locate the index of the nth last occurrence, encapsulated within an OptionalInt.

Upon obtaining the result, we extract the index from the OptionalInt and validate its accuracy against the expectedIndex.

This functional programming approach not only offers a more expressive and concise solution but also aligns with modern programming paradigms emphasizing immutability and function composition.

4. Conclusion

In this article, we’ve explored different methods to find the nth last occurrence of a character within a string using Java. We’ve covered both traditional looping techniques and functional programming approaches leveraging Java streams.

As always, the complete code samples for this article can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments