Locating Neighbouring Words and Characters

Learn how to locate the left and right neighboring words of a string.

We will look at together is retrieving neighboring words from arbitrary positions. For example, given the sentence The quick brown fox jumped over the lazy dog, if we supplied position 6, we might want to be able to retrieve the word The on the left and the word brown on the right. There are a few ways we could approach implementing this. The first idea is to update our previous wordAt implementation and skip collecting the characters to return until we’ve reached a word boundary.

The approach of waiting until we’ve seen a word boundary works but involves keeping track of additional states, which can quickly get messy. A more elegant solution is to retrieve the position of the neighboring nonword boundary character and then use that position in a call to our existing wordAt helper method.

Locating the word toward the left side

To begin, we will start by retrieving the position of the next nonword boundary character to the left of our target position. This implementation will feel familiar because it is a stripped-down version of our wordAt helper method but only focuses on scanning backward through our input string. The code snippet below provides an implementation of retrieving the end position of the word before our desired position:

Get hands-on with 1400+ tech skills courses.