我试图实现一种方法,该方法可以查找给定字符串中集合中任何字符的第一个索引。例如,firstInSet("spring", "aeiou") 返回 3,因为 'i' 出现在集合“aeiou”中,而前面的字符没有出现。此外,如果没有匹配或为 null,则应返回 -1。这是我的代码。有什么问题吗?(顺便说一句,这是我第一次提问,如果我违反了任何规则,我很抱歉)
public class Strings
{
/**
Finds the first occurrence of any of the characters in a set.
@param str the string to search
@param set the set of characters to match
@return the index of the first character in str that occurs in set,
or -1 if there is no match or one of the arguments is null
*/
public int firstInSet(String str, String set)
{
for (int i = 0; i < set.length(); i++ )
{
for (int j = 0; j < str.length(); j++)
{
if( set.substring(i,i+1) == str.substring(j,j+1) )
{
return set.indexOf(i);
}
}
}
return -1;
}
}
最佳答案
据我了解,您想要找到 set
中 str
中的字符的第一个索引。因此,如果您有字符串 str = "unknown"
。第一个 u 的答案为 0。
public static int firstInSet(String str, String set) {
int pos = 0;
for (char c : str.toCharArray()) {
int i = set.indexOf(c);
if (i >= 0) {
return pos;
}
pos++;
}
return -1;
}
关于java - 我试图实现一种方法,该方法可以查找给定字符串中集合中任何字符的第一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59418403/