2014-04-22 22 views
0

有沒有更簡短的方法來確定您的字符串是否包含String []中的任何值?找出一個字符串是否包含Java中的數組中的值

這是我的代碼:

String s = "Hello world! My name is Bao."; 
String[] arr = new String[]{"o", "!", "-", "y", "z"}; 
for (String item : arr) { 
    if (s.contains(item)) { 
     System.out.println("String s contains: " + item); 
    } else { 
     System.out.println("String s doesn't contains: " + item); 
    } 
} 

是否有這樣做的一個較短的方法嗎?我不想爲此使用for循環。

當數組包含4000多個字符串時,它可能會很慢。

+1

調查Aho Corasick。 –

+2

這取決於你的意思是慢。 4000沒什麼。另一方面400萬美元.. – keyser

+0

你能更具體地說明你的意思嗎?執行時間更短?較短的代碼? –

回答

0

對於大型字符串數組,首先將數組和目標字符串轉換爲HashSet。成爲Set將刪除重複的字符,並且Hash ed會使比較非常快。然後你可以做幾個快速設置減法來得到你的答案:

String s = "Hello world! My name is Bao."; 
String[] arr = new String[] { "o", "!", "-", "y", "z" }; 

Set<String> sSet = new HashSet<String>(Arrays.asList(s.split("(?!^)"))); 
Set<String> arrSet = new HashSet<String>(Arrays.asList(arr)); 

Collection<String> notFound = CollectionUtils.subtract(arrSet, sSet); 
Collection<String> found = CollectionUtils.subtract(arrSet, notFound); 
相關問題