我试图在Java中创建一个方法,该方法给我在字符串中出现char的第n个索引。 例 字符串Hello =“ allo大家好吗” 如何获得第三个“ Y”的索引? 谢谢
hdswphr 回答:在Java中如何获取没有数组唯一字符串类的char的第二次或第n次出现的索引
final String text = "allo every body how are you";
int n = 3;
final char toFind = 'y';
int index = 0;
while (index < text.length()) {
if (text.charAt(index) == toFind) {
n--;
if (n == 0)
break;
}
index++;
}
// index is 24
System.out.print(index);
,
public static int findIndex(String string,char c,int n)
{
int len = string.length();
return IntStream.range(0,len)
.filter(i -> c == string.charAt(i))
.skip(n-1)
.findFirst()
.orElse(-1); // No element found
}