简体   繁体   中英

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

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.

首先将所有字符串都转换为大写或小写,然后使用startsWith()方法。

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.

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

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.

Try This Logic For Basic

    Scanner sc=new Scanner(System.in);

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

    System.out.println("Enter Characters");

    String matchCharStr = sc.next();

    for (int i = 0; i < s.length; i++) {
        if (s[i].toLowerCase().contains(matchCharStr.toLowerCase())) {
            System.out.println(s[i]);
        }
    }

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