Domanda

The title may be a little confusing or misleading but I'm trying to compare a single string:

String mystring = "abc";

And then try to compare it with every single string contained in an arraylist

ArrayList<String> array = new ArrayList<String>();
array.add("The first letters of the alphabet are abc");
array.add("abc");
array.add("Alphabet");
array.add("Nothing");

But (and I'm not certain) it seems that contains is true only if both strings matches and not if the word or phrase is inside the string.

How can I compare a desired string to a "phrase" that is within an ArrayList of strings?

È stato utile?

Soluzione

To check what you're asking for, you would have to iterate through the values that are contained in the array, and check whether they contain the value of the string that you want to check.

for (String fromArray : array) {
    if (fromArray.contains(mystring)) {
        // put your code here
    }
}

This method is case sensitive. To overcome this, you can either change the strings to lowercase (with the toLowerCase() method), or use a library that has been designed to do so. One such library is the Apache Commons library.

http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#containsIgnoreCase%28java.lang.CharSequence,%20java.lang.CharSequence%29

If you want to check whether the array element, instead of containing, instead matches the string you want to check it against, you would use the matches() method.

Documentation links:

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Apache commons StringUtils

Altri suggerimenti

try this

// check if string is exist in array
if(array.Contains("YourString"))
{
// if contain then u can use this or do operations
Response.Write("YourString is available in array");
}

this will help you

It's simple.

You use an Iterator over the ArrayList.

for(String s: array):
  if(s.toLowerCase().contains(myString.toLowerCase())) { //find if such a substring exits within each string
      //do something
    }
}

If however you don't want to check case sensitive-ness you get remove the toLowerCase() from the lines.

I hope you are aware of what toLowerCase() does and putting it in the code doesn't makes a difference for you.

You need iterate through all the elements of Array List and then need to check using contains() method

for (String str : array){
            if(str.contains(mystring)){
                System.out.println(str + " Conatins" + mystring);
            }
        }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top