简体   繁体   English

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

[英]Search String in an arrayed text file

I took a text file and put it in one array. 我拿了一个文本文件并把它放在一个数组中。 However, I want to search for a String (word) within the array. 但是,我想在数组中搜索String(word)。 In my case I wanted to use the scanner to get input from the user, then search for a string match in the array. 在我的情况下,我想使用扫描仪从用户获取输入,然后在数组中搜索字符串匹配。 How can one achieve such a task? 如何才能实现这样的任务?

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);
}

My output: 我的输出:

[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!!
  }
}

You can use the .contains() function from List. 您可以使用List中的.contains()函数。 It will use the .equals() method of the parameter on each element 它将在每个元素上使用参数的.equals()方法

words.contains("your_string")

Just realized you are saving one line per index, and not one word. 刚刚意识到你每个索引保存一行,而不是一个单词。 In this case: 在这种情况下:

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

The equals() method suggested by others will only work if you have one word per line. 其他人建议的equals()方法只有在每行有一个单词时才有效。 Try iterating over the list and see if one (or more) of the strings contains(word) the word you are looking for? 尝试迭代列表,看看一个(或多个)字符串是否包含(word)您要查找的单词?

You can do something with the scanner like this 您可以像这样使用扫描仪

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

This isn't a full solution but hopefully this will guide you to a working solution. 这不是一个完整的解决方案,但希望这将指导您找到一个有效的解决方案。

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

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