OneBite.Dev - Coding blog in a bite size

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

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

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

This code finds the last occurrence of a character c in a string str. It starts by declaring a variable ‘lastIndex’ and setting it to -1, which indicates that the last occurrence of the character c has not been found yet. It then enters a loop, iterating through each character of the string one-by-one. Each time it finds a character that matches c, it sets the lastIndex to the current index of the string, thereby creating a record of the last occurrence. It continues looping until the end of the string is reached and it returns the lastIndex variable. If c does not appear in the string, then the loop will end and -1 is returned.

java