Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you find at what line a word is located in a textbox?

I'm currently working on a notepad that has a find option. When you type in a word it'll find it and highlight it. I got it working but I've reached a wall that I can't seem to pass with the method i'm currently using to do it. I'm currently splitting all the words in the textbox with ' ' and adding up the length of the words untill I find the inputted search term so I can see where exactly the found word was, so I can highlight it.

The problem I have now though, is that since i'm using split(' ') to get each word in the textbox, whenever the user adds a new line the split's return array will be "wordOnFirstLine\r\nwordOnSecondLine". So they will be counted as one word. What's another way I can find a word in the textbox and see where exactly it's located so I can highlight it?

like image 398
CsharpFrustration Avatar asked Oct 04 '22 02:10

CsharpFrustration


2 Answers

Try splitting the string as

string splitstring = stringToSplit.Split(new char[] { ' ', '\n', '\r' });

It'll give you an empty string in between all the '\n' and '\r' characters, but that fix may be closest to what you're currently doing.

like image 82
Stochastically Avatar answered Oct 13 '22 09:10

Stochastically


I believe you're looking for the GetLineFromCharIndex(int) method. Passing in the index of the first character in your word should return its line number.

like image 35
Mike Precup Avatar answered Oct 13 '22 09:10

Mike Precup