1#' Right split a string.
2#'
3#' Return a list of character vectors of the words in the string, using \code{sep} as the delimiter
4#' string.
5#'
6#' If \code{maxsplit} is given, at most \code{maxsplit} splits are done, the rightmost
7#' ones. If \code{sep} is not specified, any whitespace string is a separator.
8#' Except for splitting from the right, \code{pystr_rsplit} behaves like
9#' \code{\link{pystr_split}}.
10#'
11#' @param str A character vector.
12#' @param sep A character string.
13#' @param maxsplit A numeric vector.
14#'
15#' @return A list of character vectors.
16#'
17#' @references \url{https://docs.python.org/3/library/stdtypes.html#str.rsplit}
18#'
19#' @seealso \code{\link{pystr_split}}
20#'
21#' @examples
22#' pystr_rsplit("a--b--c", "--")
23#' pystr_rsplit("a--b--c", "--", 1)
24#'
25#' @export
26pystr_rsplit <- function(str, sep=" ", maxsplit=nchar(str)-1) {
27  return(mapply(pystr_rsplit_, str, sep, maxsplit, SIMPLIFY=FALSE, USE.NAMES=FALSE))
28}
29pystr_rsplit_ <- function(str, sep, maxsplit) {
30  if(maxsplit == 0) {
31    return(str)
32  }
33
34  if(sep == "") {
35    splits = strsplit(str, sep)[[1]]
36
37    if(maxsplit >= nchar(str) - 1) {
38      return(splits)
39    }
40
41    first = pystr_join(splits[1:maxsplit], "")
42    last = splits[(maxsplit + 1):length(splits)]
43    return(c(first, last))
44  }
45
46  num_splits = min(pystr_count(str, sep), maxsplit)
47  cum_splits = 0
48  elements = c()
49  remaining = str
50
51  while(cum_splits < num_splits) {
52    if(remaining == "") {return(elements)}
53    parts = pystr_rpartition(remaining, sep)[[1]]
54    elements = c(elements, parts[3])
55    remaining = parts[1]
56    cum_splits = cum_splits + 1
57  }
58
59  return(c(remaining, rev(elements)))
60}
61