简体   繁体   English

检查字符串是否包含字母

[英]Checking a String if it Contains Letters

I have a question on how to do something involving strings and lists in java. 我有一个关于如何在java中执行涉及字符串和列表的问题。 I want to be able to enter a string say for example 我希望能够输入一个字符串,例如

"aaa" “AAA”

using the scanner class and the program must return the shortest word with three a's in it. 使用扫描仪类和程序必须返回最短的单词,其中包含三个a。 So for example there is a text file filled with thousands of words that is to be checked with the input and if it has three a's in it, then it is a candidate but now it has be the shortest to return only that one. 因此,例如,有一个文本文件,其中填充了数千个要与输入一起检查的单词,如果其中有三个单词,那么它是候选者,但现在它是最短的只返回那个。 How exactly do you go about comparing and seeing if an input of letters is in all the words of a text file filled with words? 你究竟如何比较和查看一个字母输入是否在一个充满单词的文本文件的所有单词中?

Start by taking a vist to the java.lang.String JavaDocs 首先来看看java.lang.String JavaDocs的vist

In particular, take a look at String#contains . 特别是,看看String#contains I'll forgive you for missing this one because of the parameter requirements. 由于参数要求,我原谅你错过了这个。

Example: 例:

String text = //...
if (text.contains("aaa")) {...}

Try this, 尝试这个,

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

The simplest approach is to use String.contains() and a loop that checks length: 最简单的方法是使用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