Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# stringr (development version)

* `str_pad()` gains `use_length` argument to control whether to use the total code
point width or the number of code points as "width" of a string (#190).

* `str_split_fixed()` now pads with `NA` rather than `" "` (#195).

* Experimental support for display `str_view()` with ANSI escapes, which
Expand Down
10 changes: 6 additions & 4 deletions R/pad.r
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
#' @param width Minimum width of padded strings.
#' @param side Side on which padding character is added (left, right or both).
#' @param pad Single padding character (default is a space).
#' @param use_length If `TRUE`, use the number of characters instead of the
#' total of character widths (see [stringi::stri_width]).
#' @return A character vector.
#' @seealso [str_trim()] to remove whitespace;
#' [str_trunc()] to decrease the maximum width of a string.
Expand All @@ -24,12 +26,12 @@
#'
#' # Longer strings are returned unchanged
#' str_pad("hadley", 3)
str_pad <- function(string, width, side = c("left", "right", "both"), pad = " ") {
str_pad <- function(string, width, side = c("left", "right", "both"), pad = " ", use_length = FALSE) {
side <- match.arg(side)

switch(side,
left = stri_pad_left(string, width, pad = pad),
right = stri_pad_right(string, width, pad = pad),
both = stri_pad_both(string, width, pad = pad)
left = stri_pad_left(string, width, pad = pad, use_length = use_length),
right = stri_pad_right(string, width, pad = pad, use_length = use_length),
both = stri_pad_both(string, width, pad = pad, use_length = use_length)
)
}
11 changes: 10 additions & 1 deletion man/str_pad.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions tests/testthat/test-pad.r
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,11 @@ test_that("directions work for simple case", {
expect_equal(pad("left"), " had")
expect_equal(pad("both"), " had ")
})

test_that("padding based of length works", {
# \u4e2d is a 2-characters-wide Chinese character
pad <- function(...) str_pad("\u4e2d", ..., side = "both")

expect_equal(pad(width = 6), " \u4e2d ")
expect_equal(pad(width = 5, use_length = TRUE), " \u4e2d ")
})