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

如何获取字符串中字符的索引 优化查找元音位置的Java代码

Java查找字符串元音位置的简化代码方案

低版本Java兼容简化方案

去掉没必要的双层循环和元音ArrayList存储,直接用字符串存元音列表,配合indexOf方法判断即可,代码量大幅缩短:

String inputStr = "Merhaba";
ArrayList<Integer> vowelsPos = new ArrayList<>();
// 直接用字符串存储元音,需要匹配大写的话可改为 "aeiouAEIOU"
String vowelsBin = "aeiou";

for (int inputPos = 0; inputPos < inputStr.length(); inputPos++) {
    // indexOf返回-1代表不存在对应字符,非-1即命中元音
    if (vowelsBin.indexOf(inputStr.charAt(inputPos)) != -1) {
        vowelsPos.add(inputPos);
    }
}
return vowelsPos;

你之前用indexOf/contains没成功大概率是因为调用方法的参数类型不匹配:字符串的contains方法只接收CharSequence类型参数,不能直接传入char类型,需要转成字符串才能用,写法是vowelsBin.contains(String.valueOf(inputStr.charAt(inputPos))),和上面indexOf的判断效果一致。

Java 8+ 流极简写法

如果你使用JDK8及以上版本,可以用流进一步把代码压缩到单行返回:

import java.util.stream.IntStream;
import java.util.stream.Collectors;

// 方法内部逻辑
String inputStr = "Merhaba";
String vowelsBin = "aeiou";
return IntStream.range(0, inputStr.length())
        .filter(i -> vowelsBin.indexOf(inputStr.charAt(i)) != -1)
        .boxed()
        .collect(Collectors.toList());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 21:24:04