Ryan Peschel
Ryan Peschel

Reputation: 11996

How to find the start and end index of a word based on a given index within the word?

For example, if there was a TextBox that contained this text:

The quick brown fox jumped over the lazy dog.

And the blinking cursor (text caret) of the textbox was located at the i in quick, what would be an elegant way of finding the index for the q and the index for the k?

Basically, given a position in the string, how would I find the index of the beginning and end of the word? If the given index is a space assume it uses the previous word.

I have a really hackish solution using loops going in both direction until each finds a space but it's really messy and I was wondering if there was a more simplistic way to approach the problem. It's late so I feel like I may be missing something obvious here.

Thanks for the help.

Upvotes: 1

Views: 4000

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500065

Using loops in both directions sounds like the right approach to me - but you don't need to write the loops. You can use String.IndexOf and String.LastIndexOf:

int nextSpace = text.IndexOf(' ', index);
int previousSpace = text.LastIndexOf(' ', index);

It will be fiddly, and you should also consider that words don't always break at space boundaries - but that should at least get rid of your loops :)

Upvotes: 4

Related Questions