如何获取字符串中字符的索引 优化查找元音位置的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
相关产品推荐
相关产品推荐

