繁体   English   中英

检查字符串是否包含字母

[英]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.

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