File: trunc.R

package info (click to toggle)
r-cran-stringr 1.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,112 kB
  • sloc: javascript: 11; sh: 9; makefile: 2
file content (56 lines) | stat: -rw-r--r-- 1,504 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#' Truncate a string to maximum width
#'
#' Truncate a string to a fixed of characters, so that
#' `str_length(str_trunc(x, n))` is always less than or equal to `n`.
#'
#' @inheritParams str_detect
#' @param width Maximum width of string.
#' @param side,ellipsis Location and content of ellipsis that indicates
#'   content has been removed.
#' @return A character vector the same length as `string`.
#' @seealso [str_pad()] to increase the minimum width of a string.
#' @export
#' @examples
#' x <- "This string is moderately long"
#' rbind(
#'   str_trunc(x, 20, "right"),
#'   str_trunc(x, 20, "left"),
#'   str_trunc(x, 20, "center")
#' )
str_trunc <- function(
  string,
  width,
  side = c("right", "left", "center"),
  ellipsis = "..."
) {
  check_number_whole(width)
  side <- arg_match(side)
  check_string(ellipsis)

  len <- str_length(string)
  too_long <- !is.na(string) & len > width
  width... <- width - str_length(ellipsis)

  if (width... < 0) {
    cli::cli_abort(
      tr_(
        "`width` ({width}) is shorter than `ellipsis` ({str_length(ellipsis)})."
      )
    )
  }

  string[too_long] <- switch(
    side,
    right = str_c(str_sub(string[too_long], 1, width...), ellipsis),
    left = str_c(
      ellipsis,
      str_sub(string[too_long], len[too_long] - width... + 1, -1)
    ),
    center = str_c(
      str_sub(string[too_long], 1, ceiling(width... / 2)),
      ellipsis,
      str_sub(string[too_long], len[too_long] - floor(width... / 2) + 1, -1)
    )
  )
  string
}