java - 我试图实现一种方法,该方法可以查找给定字符串中集合中任何字符的第一个索引

标签 java methods

我试图实现一种方法,该方法可以查找给定字符串中集合中任何字符的第一个索引。例如,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;
       }
    }

最佳答案

据我了解,您想要找到 setstr 中的字符的第一个索引。因此,如果您有字符串 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/

相关文章:

Java - 类方法可以看到同类参数的私有(private)字段

java - 出现奇怪的 java.lang.NoSuchMethodError 错误

java - 为什么我的程序只打印一个成绩?

java - 使用多个定界符Java分割字符串

Eclipse 中的 Java Jsoup 程序抛出 java.net.SocketTimeoutException : connect timed out

java - 如何使用 Jersey + JAXB + JSON 传输原始列表

javascript - JS重命名方法

java - 使用空格分析器搜索关键字

Java System.out.println 格式

Java字符串方法不返回字符串