1

I cannot seem to figure out how to do this.. I'm stuck. I can solve it in my head but i can't figure out how to write the code. I know this code probably isn't even close to right, but I'm not sure if the easiest way to go about this is to convert the chars string into a character array or if I'm close here?

I know that what I wrote is wrong but I just wanted to write it out like that because it's basically what I'm trying to do. Your help is appreciated!

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;
        }
    }
 }
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
Matt Shade
  • 55
  • 6
  • What didn't work? Not the correct result? An error? – assylias Mar 12 '18 at 21:47
  • Possible duplicate of [How can I check if a single character appears in a string?](https://stackoverflow.com/questions/506105/how-can-i-check-if-a-single-character-appears-in-a-string) – Garret Mar 12 '18 at 21:51

3 Answers3

1

Assuming you have to check every characters in chars and you don't want to make other assumptions e.g. removing duplicated checks:

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;
}
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
0

use

string.indexOf(char) > -1

in replacement of the for loop

public static int indexOfAny(String s, String chars) {
    if(string.indexOf(chars) > -1)
       return string.indexOf(chars);
    else
       return -1;
}

of if chars has multiple chars to check seperately

for (char c : chars.toCharArray()) {
     if(string.indexOf(c) > -1)
       return string.indexOf(c);
}
return -1;

you dont even need the function indexOfAny honestly..

Garret
  • 144
  • 12
0

You need to iterate over all characters inside chars rather than checking for string equality with each character in s.

public static int indexOfAny(String s, String chars) {

    for (int i = 0; i < s.length(); i++) {
        for (int j = 0; j < chars.length(); j++) {

            if (s.charAt(i) == chars.charAt(j)) {

                return i;
            }
        }
    }

    return -1;
}

Or a bit shorter:

public static int indexOfAny(String s, String chars) {

    for (char c : chars.toCharArray()) {

        int i = s.indexOf(c);
        if (i >= 0) { return i; }
    }

    return -1;
}
Deconimus
  • 85
  • 5