1#' Find the highest index of a substring.
2#'
3#' Return the higest index in the string where substring \code{sub} is found,
4#' such that \code{sub} is contained in the slice \code{substr(str, start, end)}.
5#'
6#' @param str A character vector.
7#' @param sub A character vector.
8#' @param start A numeric vector.
9#' @param end A numeric vector.
10#'
11#' @return A numeric vector. \code{-1} indicates \code{sub} was not found.
12#'
13#' @references \url{https://docs.python.org/3/library/stdtypes.html#str.rfind}
14#'
15#' @seealso \code{\link{pystr_find}}
16#'
17#' @examples
18#' pystr_rfind("abcdxyzabc", "abc")
19#' pystr_rfind("abc", "xy")
20#' pystr_rfind("abcxyzabc", "abc", 4)
21#'
22#' @export
23pystr_rfind <- function(str, sub, start=1, end=nchar(str)) {
24  return(mapply(pystr_rfind_, str, sub, start, end, USE.NAMES=FALSE))
25}
26
27pystr_rfind_ <- function(str, sub, start, end) {
28  string_to_check = substr(str, start, end)
29
30  for(i in nchar(string_to_check):1) {
31    start_check = i - nchar(sub) + 1
32    end_check = i
33    letters_to_check = substr(string_to_check, start_check, end_check)
34
35    if(letters_to_check == sub) {
36      return(start_check + start - 1)
37    }
38  }
39
40  return(-1)
41}
42