【发布时间】:2013-01-03 07:38:30
【问题描述】:
我有一个程序,它接受用户输入并将每个单词存储在 arrayList 中,然后在外部文件中搜索每个单词。我想要从这里做的是返回另一个词(在另一个数组列表中)或价格值在与第一个搜索词相同的行中。
例如:
Here is my user input: Tuna
Here are my associated words in another arrayList: (seared, chunky, shredded)
Here are lines in my file: the cost of seared tuna is $1 per tin. Contains brine.
the cost of shredded tuna is $50 per packet
然后我希望我的程序在每一行中搜索 tuna,然后打印出来:
Seared $1
Shredded $50
为了让我的程序执行此操作,我需要它了解单词 seared 在金枪鱼出现的第一行中,并且该行中的货币价值是 1 美元。然后为下一行重复该过程。
我需要知道的主要事情是缓冲阅读器是否区分不同的行,以及我是否可以在每行分别搜索我在 arrayList 中的单词和货币值。
我用于搜索的代码如下。到目前为止,它只在文件中搜索一个单词,然后返回该单词的位置。
while((strLine1 = br1.readLine()) != null){
for(String list: listOfWords){
Pattern p = Pattern.compile(list);
Matcher m = p.matcher(strLine1);
int start = 0;
while (m.find(start)) {
System.out.printf("Word found: %s at index %d to %d.%n", m.group(), m.start(), m.end());
start = m.end();
}
}
}
我希望这更容易理解。
【问题讨论】:
-
我认为你应该使用不区分大小写的搜索,我也会使用
contains或indexOf方法而不是正则表达式:strLine1.toLowerCase().contains(list.toLowerCase())。 -
你能解释一下实际的问题是什么吗?看来您知道如何逐行读取文件并逐行搜索单词。你有什么疑问?