简体   繁体   中英

String .equals method not working (String object)

I am trying to split a line of String text into an array, and perform an SQLite3 query on String elements that don't equal words such as "a", "to", or "on".

Here is the method I am using that splits a String into an array:

public static String[] extract(String string) {
    String[] splitArray = null;
    try {
        splitArray = string.split("\\s+");

    } catch (PatternSyntaxException ex) {
        ex.printStackTrace();
    }
    return splitArray;
}

Next, using a for loop I am trying to run a queries on parts of the array that don't include the aforementioned words:

String garlic = "1 small garlic clove, finely grated on a microplane";
String[] queryArray = extract(garlic);
for (int i = 0; i < queryArray.length; i++ ) {
if (!queryArray[i].equals("a") || !queryArray[i].equals("to") {
   performQuery(queryArray[i]);
}

I have tried calling .trim(); on the array element, but these String are still being queried despite seeming to be equivalent to the code.

The initial String has been copy pasted from a website - does that have any effect vs. just typing the String out? Copying and pasting from the website is necessary for my program so please give advice on how to work with that. If tried copying the a line from a webpage into a new String object, and then retyping the same line out, and I get the same result.

Please help!

Cheers.

Every string will be not equal to at least one of ["a", "to"] . what you want is an && operator between your two conditions.

if (!queryArray[i].equals("a") && !queryArray[i].equals("to")) {
   performQuery(queryArray[i]);
}

Your condition if (!queryArray[i].equals("a") || !queryArray[i].equals("to") means that the String has to be different of a OR different of to so it'll be always true ( to is different of a ), you need to use &&

But you says that there is also on , to avoid a long condition, you can do :

String garlic = "1 small garlic clove, finely grated on a microplane";
String[] queryArray = extract(garlic);
List<String> toAvoid = Arrays.asList("a", "to", "on");
for (int i = 0; i < queryArray.length; i++ ) {
    if (!toAvoid.contains(queryArray[i])) {
        performQuery(queryArray[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