简体   繁体   English

如何检查数组是否包含字符串中的特定单词并获取它?

[英]How to check if an Array contains a particular word in a String and get it?

I have a String[] and an input String : 我有一个String[]和一个输入String

String[] ArrayEx = new String[1];
String textInput = "a whole bunch of words"

What I want to do is check if the String contains a word present in the Array , like this. 我想要做的是检查String包含Array存在的单词,像这样。

Ex: textInput = "for example" and ArrayEx[0] = "example" 例如: textInput = "for example" and ArrayEx[0] = "example"

I know about this method: 我知道这种方法:

Arrays.asList(yourArray).contains(yourValue)

but it checks the full String right? 但是它检查完整的String正确吗? How do I check if the String contains a particular word present in the Array. 如何检查String包含数组中存在的特定单词 Even if it is from an ArrayList I have no problem. 即使它来自ArrayList我也没有问题。

Also if yes, can I get that word from the String[] ? 另外,如果可以,我可以从String[]获取该单词吗? ie, in the above case get the String "example". 即,在上述情况下,获取String “ example”。

EDIT: 编辑:

public void searchNearestPlace(String v2txt)
{
    Log.e("TAG", "Started");
    v2txt = v2txt.toLowerCase();
    String[] places = {"accounting, airport, amusement_park, aquarium, art_gallery, atm, bakery, bank, bar, beauty_salon, bicycle_store, book_store, bowling_alley, bus_station, cafe, campground, car_dealer, car_rental, car_repair, car_wash, casino, cemetery, church, city_hall, clothing_store, convenience_store, courthouse, dentist, department_store, doctor, electrician, electronics_store, embassy, establishment, finance, fire_station, florist, food, funeral_home, furniture_store, gas_station, general_contractor, grocery_or_supermarket, gym, hair_care, hardware_store, health, hindu_temple, home_goods_store, hospital, insurance_agency, jewelry_store, laundry, lawyer, library, liquor_store, local_government_office, locksmith, lodging, meal_delivery, meal_takeaway, mosque, movie_rental, movie_theater, moving_company, museum, night_club, painter, park, parking, pet_store, pharmacy, physiotherapist, place_of_worship, plumber, police, post_office, real_estate_agency, restaurant, roofing_contractor, rv_park, school, shoe_store, shopping_mall, spa, stadium, storage, store, subway_station, synagogue, taxi_stand, train_station, travel_agency, university, veterinary_care, zoo"};
    int index;
    for(int i = 0; i<= places.length - 1; i++)
    {
        Log.e("TAG","for");
        if(v2txt.contains(places[i]))
        {
            Log.e("TAG", "sensed?!");
            index = i;
    }
}

Say v2txt was "awesome airport" the sensed Log never does appear even though all other logs indicate it working v2txt"awesome airport" ,即使其他所有日志都表明它可以正常工作,但感觉v2txt的日志从未出现

Edit2: 编辑2:

I am so embarrassed that I made such a dunder head mistake. 我很尴尬,以至于我犯了一个笨拙的错误。 My array is declared wrongly. 我的数组声明错误。 There should be a " before every , . I am such a big idiot! Sorry will change it and let you know. 应该有一个"每之前,我是这样一个大白痴!对不起会改变它,让你知道。

First of all it has nothing to do with android 首先,它与android无关

Second the solution 第二解决方案

boolean flag = false;
String textInput = "for example";
int index = 0;
String[] yourArray = {"ak", "example"};
for (int i = 0; i <= yourArray.length - 1; i++) {

    if (textInput.contains(yourArray[i])) {
        flag = true;
        index = i;

    }
}
if (flag) 
   System.out.println("found at index " + index);
else 
   System.out.println("not found ");

DEMO 演示

EDIT : 编辑

Change your array to 将数组更改为

String[] places = {"accounting", "airport", "amusement_park" };

and so on with other values with your array declaration it has one index. 以此类推,在数组声明中带有其他值,它只有一个索引。

you can split your string and get array of words 您可以拆分字符串并获取单词数组

txArray = textInput.split(" ");

then for each element in txArray check if 然后对于txArray中的每个元素检查

Arrays.asList(ArrayEx).contains(txArray[i])

Try this; 尝试这个;

Sting text2check = "Your Name": 字符串text2check =“您的姓名”:

for(int t = 0; t < array.length; t++)
{
if (text2check.equals(array[t])
// Process it Here
break;
}

This will take an String array, and search through all the strings looking for a specific char sequence found in a string. 这将采用String数组,并搜索所有字符串以查找字符串中找到的特定char序列。 Also, native Android apps are programmed in the Java language. 另外,本机Android应用程序使用Java语言编程。 You might find it beneficial to read up more on Strings . 您可能会发现对Strings的更多阅读有益。

String [] stringArray = new String[5];
//populate your array
String inputText = "abc";
for(int i = 0; i < stringArray.length; i++){
    if(inputText.contains(stringArray[i]){
        //Do something
    }
}
txArray = "Hello I'm your String";
String[] splitStr = txArray.split(" ");
int i=0;
while(splitStr[i]){
if(Arrays.asList(ArrayEx).contains(txArray[i])){
System.out.println("FOUND");
}
i++;
}

You can use Java - Regular Expressions. 您可以使用Java-正则表达式。

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. 正则表达式是特殊的字符序列,可使用模式中保留的特殊语法来帮助您匹配或查找其他字符串或字符串集。 They can be used to search, edit, or manipulate text and data. 它们可用于搜索,编辑或处理文本和数据。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Testing {

    public static void main(String[] args) {

        String textInput = "for example";
        String[] arrayEx = new String[1];
        arrayEx[0] = "example";

        Pattern p = Pattern.compile(arrayEx[0]);
        Matcher m = p.matcher(textInput);
        boolean matchedFoundStatus = false;
        while (m.find()) {
            matchedFoundStatus = true;
        }
        System.out.println("matchedFoundStatus:" + matchedFoundStatus);
    }

}

"How do I check if the String contains a particular word present in the Array?" “如何检查字符串是否包含数组中存在的特定单词?” is the same thing as Is there an element in the array, for which the input string contains this element 与数组中是否存在元素相同,输入字符串为此元素包含该元素

Java 8 Java 8

String[] words = { "example", "hello world" };
String input = "a whole bunch of words";

Arrays.stream(words).anyMatch(input::contains);

(The matching words can also be extracted, if needed:) (如果需要,还可以提取匹配的单词:)

Arrays.stream(words)
      .filter(input::contains)
      .toArray();

If you are stuck with Java 7, you will have to re-implement "anyMatch" and "filter" yourself: 如果您坚持使用Java 7,则必须自己重新实现“ anyMatch”和“ filter”:

Java 7 Java 7

boolean anyMatch(String[] words, String input) {
    for(String s : words)
        if(input.contains(s))
            return true;
    return false;
}

List<String> filter(String[] words, String input) {
    List<String> matches = new ArrayList<>();
    for(String s : words)
        if(input.contains(s))
            matches.add(s);
    return matches;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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