I'm trying to iterate through a JTextArea and get the line where a specific word is written so I can insert the line number into a table or an array but I don't have a clear idea on how to address it.
I haven't tried too much until now for the same reason that I don't have the idea of how to do it.
To do that, you will need to get the text of the JTextArea. Here, I will put it as an array where each line in the array is a line in the JTextArea. I found this code from this guy on stackoverflow.
This uses regexes, kinda hard to explain so there’s the documentation for you.
Afterwards, you can loop through the lines of the array and look for x word. To find x word in a string, you can use
String.contains(String);Here, the line where the word is located is
i.There is a problem though. There could be multiple of the same word. There are multiple ways to fix this: keep the last one; keep the first one; keep of them; and many others.
To keep the last one, you could assign a variable to the value of
i. As that variable’s would get changed each time that word comes up, the last time the word would appear would be the value of that variable.To keep the first one, you can create a boolean variable that is first assigned to true and when you find the word in the string, simply put it to false. Add an if statement and yeah, should work.
To keep all of them, you can make an array and add the value of
ito the array when you find the word in the string.If you would like to learn more about the the JTextArea, you can look here!
This is one of my first answer, please forgive me for any misspellings of any errors in my explaining. Thanks!