[英]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 test1 test2 test3
test4 test5 test6 test4 test5 test6
Position of test5 would be (2,8) test5的位置应为(2,8)
Using Java 8, simple solution is :- 使用Java 8,简单的解决方案是:
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. 逐行读取文件并将其放入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.
当您在元素中找到文本时,匹配行的行号将为arrayInex +1,文本的位置将为在该行中找到该文本的索引。 Hope this helps
希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.