繁体   English   中英

搜索阵列文本文件中的字符串

[英]Search String in an arrayed text file

我拿了一个文本文件并把它放在一个数组中。 但是,我想在数组中搜索String(word)。 在我的情况下,我想使用扫描仪从用户获取输入,然后在数组中搜索字符串匹配。 如何才能实现这样的任务?

public static void main(String[]args) throws IOException
{
    //Scanner scan = new Scanner(System.in);
    //String stringSearch = scan.nextLine();
    List<String> words = new ArrayList<String>();
    BufferedReader reader = new BufferedReader(new FileReader("File1.txt"));
    String line;
    while ((line = reader.readLine()) != null) {
                    words.add(line);        
        }
        reader.close();
        System.out.println(words);
}

我的输出:

[CHAPTER I. Down the Rabbit-Hole, Alice was beginning to get very tired of sitting by her sister on the, bank, and of having nothing to do:]
for(int i = 0; i < words.size(); i++){
  if(words.get(i).equals(string)){
     found!!
  }
}

您可以使用List中的.contains()函数。 它将在每个元素上使用参数的.equals()方法

words.contains("your_string")

刚刚意识到你每个索引保存一行,而不是一个单词。 在这种情况下:

for(String sLine : words) {
    if (sLine.contains("your_string")) {
         System.out.println("Got a match");
         break;
     }
 }

其他人建议的equals()方法只有在每行有一个单词时才有效。 尝试迭代列表,看看一个(或多个)字符串是否包含(word)您要查找的单词?

您可以像这样使用扫描仪

Scanner sc = new Scanner(new File("File1.txt"));
String targetString = "whatYouWant";
String testString = sc.next();
while(sc.hasNext())
{
    if(testString.equals(targetString))
        hooray!
}

这不是一个完整的解决方案,但希望这将指导您找到一个有效的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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