OneBite.Dev - Coding blog in a bite size

find the first occurrence of a character in a string in java

Code snippet on how to find the first occurrence of a character in a string in java

public static int firstIndexOf(String s, char c) {
  for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) == c) {
      return i;
    }
  }
  return -1;
}

This code takes two parameters: a String (s) and a char (c). It then loops through the given String and checks each character of the string to see if it matches the given char. If it does, the code will return the index of the character, otherwise it will return -1.

In our example, the code first creates a loop using the for statement. It starts from the 0th index and runs until it reaches the length of the String (s.length()). Inside the loop, the code uses the charAt method to check the current character of the string against the given char. If the two match, it returns the index of the character and stops the loop, otherwise it will continue to the next. Finally, if the loop finishes and no match is found, then the code returns -1.

java