user2045470
user2045470

Reputation: 59

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?

Upvotes: 0

Views: 2815

Answers (3)

Bohemian
Bohemian

Reputation: 424993

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.

Upvotes: 0

newuser
newuser

Reputation: 8466

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

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347194

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")) {...}

Upvotes: 2

Related Questions