3

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

Socrates
  • 8,724
  • 25
  • 66
  • 113
Crazymango
  • 111
  • 1
  • 1
  • 7
  • 2
    Java's `String` has the `contains` function. Did you search the internet before asking a question? It's pretty basic stuff. Edit: oh yeah, as barbakini said in his answer, if you want the search to be case-insensitive you have to make the search term and the words all uppercase or lowercase and then use `contains`. – nonzaprej May 03 '17 at 12:33

5 Answers5

3
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.

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78
1

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.

1

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

dumbPotato21
  • 5,669
  • 5
  • 21
  • 34
0

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

barbakini
  • 3,024
  • 2
  • 19
  • 25
0

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.

Rudy B
  • 68
  • 5