[英]Comparing a string to a part of string inside an arraylist
標題可能有點混亂或誤導,但我正在嘗試比較單個字符串:
String mystring = "abc";
然后嘗試將其與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");
但是(而且我不確定),似乎只有當兩個字符串都匹配時,contains才是正確的,而不是單詞或短語在字符串中時才包含。
如何將所需的字符串與字符串ArrayList
中的“短語”進行比較?
要檢查您要的內容,您必須遍歷數組中包含的值,並檢查它們是否包含要檢查的字符串的值。
for (String fromArray : array) {
if (fromArray.contains(mystring)) {
// put your code here
}
}
此方法區分大小寫 。 為了克服這個問題,您可以將字符串更改為小寫(使用toLowerCase()
方法),也可以使用為此目的設計的庫。 這樣的庫之一就是Apache Commons庫。
如果要檢查數組元素(而不是包含數組)是否匹配要檢查的字符串,則可以使用matches()
方法。
文檔鏈接:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
嘗試這個
// 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");
}
這會幫助你
這很簡單。
您在ArrayList上使用迭代器。
for(String s: array):
if(s.toLowerCase().contains(myString.toLowerCase())) { //find if such a substring exits within each string
//do something
}
}
但是,如果您不想檢查是否區分大小寫,則可以從行中刪除toLowerCase()。
我希望您知道toLowerCase()的作用,並將其放入代碼中對您沒有影響。
您需要遍歷數組列表的所有元素,然后需要使用contains()
方法進行檢查
for (String str : array){
if(str.contains(mystring)){
System.out.println(str + " Conatins" + mystring);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.