You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中查找包含指定子串的数组元素的索引?

解决Java中查找包含指定子串的数组元素索引问题

嘿,我来帮你搞定这个问题!首先咱们先梳理下你代码里的两个关键问题:

  • 变量名拼写错误:creditTIDstatusArry应该是creditTIDstatusArray,这个小失误会直接导致编译报错;
  • indexOf()方法的局限性:这个方法只做精确匹配,你的searchValue是"99802002-1",而目标元素是"99802002-1-09102842369",两者不完全相等,所以返回-1,达不到你要的效果。

要找到包含指定子串的元素索引,咱们需要主动遍历列表,逐个检查元素是否包含目标子串。这里给你两种实用的实现方式:

方式一:传统for循环(兼容性拉满,适合所有Java版本)

String[] creditTIDstatusArray = {"93312263-1-09722612223", "99802001-1-09102842369", "99802002-1-09102842369"};
// 直接用ArrayList构造器初始化列表,比addAll写法更简洁
List<String> creditTIDstatusList = new ArrayList<>(Arrays.asList(creditTIDstatusArray));
String searchValue = "99802002-1";
int retval = -1; // 默认没找到返回-1

// 遍历列表,逐个检查元素是否包含目标子串
for (int i = 0; i < creditTIDstatusList.size(); i++) {
    if (creditTIDstatusList.get(i).contains(searchValue)) {
        retval = i;
        break; // 找到第一个匹配的元素就退出循环,提升效率
    }
}

System.out.println("The element at index is:" + retval);

方式二:Java 8+ Stream API(代码更优雅简洁)

如果你用的是Java 8及以上版本,用Stream API可以写出更简洁的代码:

String[] creditTIDstatusArray = {"93312263-1-09722612223", "99802001-1-09102842369", "99802002-1-09102842369"};
List<String> creditTIDstatusList = new ArrayList<>(Arrays.asList(creditTIDstatusArray));
String searchValue = "99802002-1";

// 用IntStream生成索引,过滤出包含子串的元素索引,取第一个匹配项
OptionalInt index = IntStream.range(0, creditTIDstatusList.size())
        .filter(i -> creditTIDstatusList.get(i).contains(searchValue))
        .findFirst();

int retval = index.orElse(-1); // 没找到匹配项时返回-1
System.out.println("The element at index is:" + retval);

这两种方式都会输出你预期的2,完美解决问题!

内容的提问来源于stack exchange,提问作者Vadiraj Hebbar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 21:57:37