简体   繁体   中英

Get position of a word in a text file (line number, position in line)

How would i be able to get the position of a word in a text file in the format (line number followed, position of first character of the word)

Ex.

test1 test2 test3

test4 test5 test6

Position of test5 would be (2,8)

Using Java 8, simple solution is :-

List<String> lines = Files.lines(Paths.get("somefile.txt")).collect(Collectors.toList());
int lineNumber = IntStream.range(0,lines.size()).filter(i -> lines.get(i).contains("test5")).findFirst().getAsInt();
int charPosition = lines.stream().filter(l->l.contains("test5")).map(l-> l.indexOf("test5")).findFirst().get();

Read the file line by line and put into a ArraList. Then iterate through the list and search for the occurence of the search text in each element of the list. When you find the text in an element then, the line number of the matched line would be arrayInex +1 and position of the text will be index at which the text is found in the line. Hope this helps

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