简体   繁体   中英

How to get start position and end position of line in a string

I have a text with multiple lines and i have the line number as an input now i'd like to have the start position and end position of that line, here is what i already did but it's not working:

        private int[] getPos(int line) {
            String[] lines = textArea.getText().split(System.getProperty("line.separator"));
            int i=0;
            int pos = 0;
            while( i < lines.length){
                if(i==line)
                    break;
                pos = pos+lines[i].length();

                i++;
            }

            int[] s = {pos,pos+lines[i].length()};
            return s;
        }

example of text:

line1
line2
line3

i want to use the result to highlight the line:

textArea.getHighlighter().addHighlight(startPos, endPos,highlightPainter);
jText.getText().indexOf( lines[i] )

This will give you the start position. Add the line length to that and you have the end.

Cheers

EDIT: If there are duplicated lines, you may have to tweak the code a bit to either get the first or last line it finds.

If you want to extract the first instance of the substring (or are sure that there will be only one), you can use the .indexOf(String str) method:

String foo = "foo bar";
String toLookUp = "bar";
int initialPosition = foo.indexOf(toLookUp);
System.out.println("Initial Position: " + initialPosition + " end: " + initialPosition + toLookUp.length);

Alternatively:

String foo = "foo bar bar";
String toLookUp = "bar";
int initialPosition = foo.indexOf(toLookUp);
while(initialPosition != -1)
{
     System.out.println("Initial Position: " + initialPosition + " end: " + initialPosition + toLookUp.length);
     initialPosition = foo.indexOf(toLookUp, initialPosition + toLookUp.length;
}

Because your lines counter start from '1' and your array counter start from '0' you get wrong output.

You need need to add line -= 1; after int pos = 0; and you get correct output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM