OneBite.Dev - Coding blog in a bite size

find the position of the last occurrence of a substring in a string in java

Code snippet on how to find the position of the last occurrence of a substring in a string in java

  int lastIndexOf(String substring) {
  int lastIndex = -1;
  
  for (int i = 0; i < string.length(); i++) {
    if (string.indexOf(substring, i) == i) {
      lastIndex = i;
    }
  }
  return lastIndex;
}

This code uses a for loop to look through a string and find the position of the last occurrence of a substring. It starts out by setting a variable, lastIndex to -1, which is used to indicate the position when no substring is found. The for loop then iterates through each position in the string, using the indexOf method to check if the substring is at that position. If the indexOf returns the position as the same as the loop’s i variable , the substring is found and lastIndex is set to the current position. The loop continues until the end of the string is reached. Finally, the lastIndex variable is returned.

java