Splitting Strings Using Cursors
Learn how to split strings using the string cursor methods.
While our implementation works and can be expanded to handle even more complicated scenarios, writing these types of implementations each time we want to manage nested strings quickly becomes incredibly tedious. We will work throughout the remainder of this section to develop a reusable way to encapsulate this logic.
The overarching concept behind what we will build is a cursor. Our cursors will move along our string and see the current, previous, and next characters. They can either accept the new character and continue processing or reject it whenever they want to stop processing more text.
Our cursors will work in conjunction with the Utf8StringIterator
. When a cursor moves onto the next character, the main iterator will also advance by one position. This behavior allows us to use a cursor while iterating our string normally to essentially skip over parts of the string; once the cursor has completed, we can retrieve its results, and our loop continues where the cursor left off.
Splitting a string using cursors
That is quite a lot to take in, so let’s look at how our string-splitting implementation could be done using our cursor idea:
Get hands-on with 1200+ tech skills courses.