简体   繁体   English

获取单词在文本文件中的位置(行号,行中的位置)

[英]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.

相关问题 如何使用 java 从字符 position 获取文件中的行号 - How to get line number in file from the character position using java JEdi​​torPane获取行和列号处字符的位置 - JEditorPane get position for character at line and column number 按每个单词查找文本文件的行号 - Find the line number of a text file by each word 如何找到一个单词在文本文件的哪一行中,以及该单词是否存在于多行中,保存行号? - How to find a word is in which line of a text file and if the word exists in multiple line save the line number? 使用java查找文本文件中单词的行号 - Finding line number of a word in a text file using java 返回给定JTextPane位置的行号的方法? - Method that returns the line number for a given JTextPane position? 如何使用扫描仪在文本文件中切换一行的 position 和其后的行? - How can I switch the position of a line with the line after it in a text file using a Scanner? 在Java文件中特定位置的文本文件中写一个单词 - Write a word in a text file on a specific position in java 通过Java中的行号和行位置检索XML节点 - Retrieve XML node by line number and line position in Java 如何获取字符串中行的开始位置和结束位置 - How to get start position and end position of line in a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM