Yo estaba tratando de poner en práctica un método que encuentra el primer índice de cualquier carácter de un conjunto en una cadena dada

Erengaz feliz:

Yo estaba tratando de poner en práctica un método que encuentra el primer índice de cualquier carácter de un conjunto en un ejemplo string.For dado, firstInSet ( "resorte", "aeiou") devuelve 3 porque 'i' se produce en el conjunto "aeiou" y los caracteres anteriores no lo hacen. Además, si no hay ninguna coincidencia o NULL debe devolver -1. Aquí está mi código. ¿Cuál es el problema? (Por cierto esta es la primera vez que estoy haciendo una pregunta, si violo las reglas, lo siento)

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;
       }
    }
WJS:

Como lo entiendo desea encontrar el primer índice de un carácter en strque se encuentra en set. Así que si usted tenía la cadena str = "unknown". La respuesta sería 0 para el primer u.

    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;
   }


Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=362244&siteId=1
Recomendado
Clasificación