OneBite.Dev - Coding blog in a bite size

search for a character in a string in java

Code snippet on how to search for a character in a string in java

  public static int charPositionInString(String sourceString, char searchChar) {
    int stringLength = sourceString.length();
    for (int i = 0; i < stringLength; i++) {
      if (sourceString.charAt(i) == searchChar) {
        return i;
      }
    }
    return -1;
  }

This code searches for the position of a specific character in a given string. The function takes two parameters: the first is a string object, and the second is a character we are searching for. First we get the length of the string, then we start a loop that runs from 0 to the length of the string. Within the loop, we use the charAt() method of the String object to compare each character with the character we are searching for. If we find a match, we return the index position of the character, otherwise we return -1.

java