2011-06-28 216 views
6

如何搜索字符串数组项目元素中的特定文本?以下是xml文件的一个例子。字符串数组名称是android。我有一些项目内的字符串数组。现在我想搜索“软件”这个词。请告诉我该怎么做?在字符串数组项目元素中搜索字符串

<?xml version="1.0" encoding="utf-8"?><resources> 
<string-array name="android"> 
    <item>Android is a software stack for mobile devices that includes an operating system, middleware and key applications.</item> 
    <item>Google Inc. purchased the initial developer of the software, Android Inc., in 2005..</item> 
</string-array> 

回答

18

我认为你要做到这一点的代码。 api中没有什么可以在整个String数组上进行文本匹配;你需要一个元素做一次:

String[] androidStrings = getResources().getStringArray(R.array.android); 
for (String s : androidStrings) { 
    int i = s.indexOf("software"); 
    if (i >= 0) { 
     // found a match to "software" at offset i 
    } 
} 

当然,你可以使用一个匹配器和模式,或者你可以通过使用索引数组迭代,如果你想知道的数组中的位置一场比赛。但这是一般的方法。

19

该方法具有更好的性能:

String[] androidStrings = getResources().getStringArray(R.array.android); 
if (Arrays.asList(androidStrings).contains("software") { 
    // found a match to "software"   
} 

Arrays.asList().contains()比使用for循环更快。

+11

这不会做OP想要的,哪些(基于发布的例子)是找到包含_inctain_单词“software”的列表元素。这只会找到_equal_(全部)单词“软件”的元素。此外,'List.contains'在内部使用循环;它不会比在你自己的代码中使用循环更快。另外你还需要额外的在'String []''周围创建'List'包装。 –

+0

它可以用于自定义对象列表吗? – ralphgabb