OneBite.Dev - Coding blog in a bite size

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

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

  last_char <- function(string, character) {
    rev_string <- stringReverse(string)
    rev_index <- stringFirstCharIndex(rev_string, character)
    if (rev_index == 0)
      return(rev_index)
    return(nchar(string) - rev_index)
  }

This code is a function that takes two arguments, a string and a character. It finds the index of the last occurrence of the character from the end of the string. The first step is to reverse the string using the stringReverse() function. Then, it finds out the index of the character using the stringFirstCharIndex() function. If this index is 0, it returns 0. Otherwise, it returns the result of subtracting the index from the length of the string. This gives the index of the last occurrence of the character from the beginning of the string.

r