简体   繁体   中英

Checking a String if it Contains Letters

I have a question on how to do something involving strings and lists in java. I want to be able to enter a string say for example

"aaa"

using the scanner class and the program must return the shortest word with three a's in it. 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

In particular, take a look at 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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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