【问题标题】:Android find array index value of a partial matchAndroid查找部分匹配的数组索引值
【发布时间】:2014-01-10 19:21:38
【问题描述】:

我正在寻找一种在 Java (Android) 中查找部分匹配的索引位置的方法。

假设我的数组是:

String ips[] = {"10.185.98.111", "192.168.0.13", "Some random IPV6 address"};  

我希望能够像 ips[].indexOf("192") 这样返回“1”而不是“-1”。

这可能吗?

【问题讨论】:

  • 所以ips[0].indexOf("192") 在那里为你返回-1?
  • @Obversity 我希望如此,看到“10.185.98.111”没有 192
  • 您是要获取字符串中给定子字符串的索引,还是包含给定子字符串的字符串的字符串数组中的索引?也就是说,当你说你希望它返回“1”时,是因为数组中位置1的String包含“192”吗?
  • @gtgaxiola 我可能应该知道最好不要在早上 6:15 在没有睡觉后访问 StackOverflow,尤其是当我一整天都在打错字的时候。
  • @Obversity 你好,来自世界的另一端!这里只是下午 2 点 45 分:D

标签: java android arrays arraylist indexof


【解决方案1】:

做你自己的功能,例如:

public int getElementThatContains(String[] ips, String key) {
    for (int i = 0; i < ips.length; i++) {
        if (ips[i].indexOf(key) >= 0) {
            return i;
        }
    }
    return -1;
}

请注意,list 的排序将决定您将获得哪个 ip。 如果您有两个带有192 的元素,则将选择更接近开头的元素。

你也可以改变:

if (ips[i].indexOf(key) >= 0) {
    return i;
}

到不同类型的匹配,例如:

ips[i].contains(key)
ips[i].startsWith(key)
ips[i].endsWith(key)

【讨论】:

    【解决方案2】:
    public void specialIndexOF(List<String> ips){
            int index=0;
                for(String s:ips){
            if(s.contains(search)){
            return index;
            }
            index++;
                }
        return -1;
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-23
      • 1970-01-01
      • 1970-01-01
      • 2015-08-02
      • 2016-08-25
      • 1970-01-01
      相关资源
      最近更新 更多