在字符串数组项元素中搜索字符串

问题描述:

如何在字符串数组项元素内搜索特定文本?以下是xml文件的示例.字符串数组名称是android.我在字符串数组中有一些项.现在,我想搜索软件"一词​​.请告诉我该怎么做?

How to search for a specific text inside a string-array item element? The following is an example of the xml file. The string-array name is android. I have some items inside the string-array. Now I want to do a search for the word "software". Please tell me how to do that?

<?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>

我假设您想在代码中执行此操作. api中没有任何东西可以对整个String数组进行文本匹配;您需要一次完成一项操作:

I assume that you want to do this in code. There's nothing in the api to do text matching on an entire String array; you need to do it one element at a time:

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
    }
}

当然,您可以使用Matcher和Pattern,或者如果您想知道匹配项在数组中的位置,可以使用索引对数组进行迭代.但这是一般的方法.

Of course, you could use a Matcher and Pattern, or you could iterate through the array with an index if you wanted to know the position in the array of a match. But this is the general approach.