srtmonkey srtmonkey - 4 months ago 9x
Android Question

Locate a line that a word is on in textedit

I am trying to figure out how to locate the line a word or phrase is on from an

. For example, lets say I have the following in an

This is line 0

This is line 1

This is line 2

Line that I want and I want to get all this information

This is line 4

Since the user can add or remove lines of text, the line of the information I want can always be on a different line. Ignoring text wrap, how would I be able to do a search for "this information" and get the line at which that text is located. This is a basic idea of what I am trying to do.

int line = /*what would I use to find the line the text is on*/
int startPos = editText.getLayout().getLineStart(line);
int endPos = editText.getLayout().getLineEnd(line);

String theLine = editText.getText().toString().substring(startPos, endPos);


You need to read the String line by line, you can do it with a Scanner:

int lineNumber = 0;
Scanner scanner = new Scanner(editText.getText().toString());
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    if(line.contains("String you want")) { 
        System.out.println(lineNumber + " " + line);