簡體   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