gpt4 book ai didi

java - 返回 String s 中 chars 中任何字符第一次出现的索引或 -1

转载 作者:行者123 更新时间:2023-11-30 06:15:44 25 4
gpt4 key购买 nike

我似乎不知道如何做到这一点..我被困住了。我可以在脑海中解决它,但我不知道如何编写代码。我知道这段代码可能不太正确,但我不确定最简单的方法是否是将字符字符串转换为字符数组,或者我是否接近这里?

我知道我写的东西是错误的,但我只是想这样写出来,因为这基本上就是我想做的事情。感谢您的帮助!

public static int indexOfAny(String s, String chars) {
for (int i = 0; i <= s.length(); i++) {
if ((s.charAt(i)).equals(chars)) {
return i;
} else {
return -1;
}
}
}

最佳答案

假设您必须检查 chars 中的每个字符,并且您不想做出其他假设,例如删除重复的检查:

public static int indexOfAny(String s, String chars) {
int i = -1;
for (char c : chars.toCharArray()) {
int pos = s.indexOf(c);
if (pos >= 0 && (pos < i || i < 0)) {
i = pos;
}
}
return i;
}

关于java - 返回 String s 中 chars 中任何字符第一次出现的索引或 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49244913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com