[英]Checking a String if it Contains Letters
我有一個關於如何在java中執行涉及字符串和列表的問題。 我希望能夠輸入一個字符串,例如
“AAA”
使用掃描儀類和程序必須返回最短的單詞,其中包含三個a。 因此,例如,有一個文本文件,其中填充了數千個要與輸入一起檢查的單詞,如果其中有三個單詞,那么它是候選者,但現在它是最短的只返回那個。 你究竟如何比較和查看一個字母輸入是否在一個充滿單詞的文本文件的所有單詞中?
首先來看看java.lang.String
JavaDocs的vist
特別是,看看String#contains
。 由於參數要求,我原諒你錯過了這個。
例:
String text = //...
if (text.contains("aaa")) {...}
嘗試這個,
while ((input = br.readLine()) != null)
{
if(input.contains(find)) // first find the the value contains in the whole line.
{
String[] splittedValues = input.split(" "); // if the line contains the given word split it all to extract the exact word.
for(String values : splittedValues)
{
if(values.contains(find))
{
System.out.println("all words : "+values);
}
}
}
}
最簡單的方法是使用String.contains()
和一個檢查長度的循環:
String search = "aaa"; // read user input
String fileAsString; // read in file
String shortest = null;
for (String word : fileAsString.split("\\s*")) {
if (word.contains(search) && (shortest == null || word.length() < shortest.length())) {
shortest = word;
}
}
// shortest is either the target or null if no matches found.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.