Crazymango
Crazymango

Reputation: 111

How to partial match with a string?

How can I type partial letters of a word to find this word?

For example: I have a string array

 String[] s = {"Cartoon", "Cheese", "Truck", "Pizza"};

if I input partial letters, such as "ca","Che" or "piz"

then I can find the whole words for the list.

Thanks

Upvotes: 3

Views: 34023

Answers (5)

Rudy B
Rudy B

Reputation: 68

Assuming you meant

String[] s = {"Cartoon", "Cheese", "Truck", "Pizza"};

The easiest option would be to iterate through your string array and do a .contains on each individual String.

for(int i = 0; i < s.length; i++){
   if(s[i].contains("car")){
      //do something like add to another list.
   }
 }

This ofcourse does not take caps into concideration. But this can easily be circumvented with .toLowerCare or .toUpperCase.

Upvotes: 0

dumbPotato21
dumbPotato21

Reputation: 5695

Try using String#startsWith

List<String> list = new ArrayList<>();
list.add("Apples");
list.add("Apples1214");
list.add("NotApples");
list.stream().map(String::toLowerCase)
             .filter(x->x.startsWith("app"))
             .forEach(System.out::println);

If you just want the String to be contained, then use String#contains

Upvotes: 1

user7953532
user7953532

Reputation:

You could use something like

String userInput = (new Scanner(System.in)).next();
for (String string : s) {
    if (string.toLowerCase().contains(userInput.toLowerCase()) return string;
}

Note that this is only going to return the first string in your list that contains whatever the user gave you so it's fairly imprecise.

Upvotes: 1

barbakini
barbakini

Reputation: 3144

First cast all your strings upper or lower case and then use startsWith () method.

Upvotes: 0

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12391

stringValue.contains("string that you wanna search");

.contains will do the job, iterate over the loop and keep adding the words in ArrayList<String> for the matched ones.

This could be a good read on string in java.

.contains is like '%word%' in mysql. There are other functions like .startsWith and .endsWith in java. You may use whatever suits the best.

Upvotes: 3

Related Questions